正确显示ajax error.responseText

Lui*_*uis 5 c# ajax asp.net-mvc jquery

我想在网页中显示 ajax 请求的错误部分中 .NET 代码中引发的异常消息:

[HttpPost]
[AllowAnonymous]
public virtual ActionResult AuthenticateUser(string somedata)
{
    throw new Exception("Ooops!!");
}
Run Code Online (Sandbox Code Playgroud)

JS代码:

        jQuery(document).ready(function () {
            jQuery.ajax(
                '@Url.Action("AuthenticateUser")',
            {
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: {
                    somedata:somedata
                },
                success: function (result) {
                    if (result == 'true') {
                        window.location = '@Url.Content(Request["returnUrl"])';
                    }
                },
                error: function (response) {
                    var responseJson = jQuery.parseJSON(response.responseText);
                    $('#errorMessage').text(responseJson.Message);

                    $('#progress_message').text("");
                },
                type: 'post'
            }
            );
        });
Run Code Online (Sandbox Code Playgroud)

我在“响应”中遇到的错误是 HTML 代码,我想解析它以获取从服务器端抛出的异常消息。所以,我想出的更好的方法是返回 Json 响应,但尽管指定“json”作为数据类型,我仍然在“响应”中收到 HTML 代码,所以......我做错了什么?问题是我从服务器端抛出的“异常”对象吗?

Lui*_*uis 0

最后我返回了 JsonResults 并处理了视图中的消息:

服务器代码:

[HttpPost]
[AllowAnonymous]
public virtual JsonResult AuthenticateUser(string somedata)
{
    if (ok)
       return new JsonResult() {Data="ok"}
    return new JsonResult() {Data= "Missing data blah"}
}
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 中:

success: function (result) {
    if (result == 'ok') {
       window.location = '@Url.Content(Request["returnUrl"])';
       return;
    }

    $('#progress_message').text("");
    $('#errorMessage').text(result);
},
Run Code Online (Sandbox Code Playgroud)