Getting properties from JsonResult on the JS side inside jquery ajax

前端 未结 1 903
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 01:49

I am returning the following object JsonResult

return new JsonResult
            {
                Data = new { ErrorMessage = message },
                Content         


        
相关标签:
1条回答
  • 2021-01-27 01:58

    How do I get the error message out of it on the jquery side?

    Since you are returning a JSON object that comes with 200 status code the error callback will never be executed. So you could use the success callback in this case:

    success: function(result) {
        if (result.ErrorMessage) {
            alert('some error occurred: ' + result.ErrorMessage);
        }
    }
    

    Or if you want the error handler to be executed make sure that you set the proper status code in your controller action:

    public ActionResult Foo()
    {
        Response.StatusCode = 500;
        return Json(new { ErrorMessage = message });
    }
    

    and then:

    error: function (jqXHR) {
        var result = $.parseJSON(jqXHR.responseText);
        alert('some error occurred: ' + result.ErrorMessage);
    }
    

    You might also find the following answer useful.

    0 讨论(0)
提交回复
热议问题