【问题标题】:Set ajax / JSon error details in a controller在控制器中设置 ajax / JSON 错误详细信息
【发布时间】:2015-05-23 20:31:44
【问题描述】:

如果我有以下看法:

$.ajax({
    url: '@PathHelper.FullyQualifiedApplicationPath(Request)' + 'Home/asdasd',
    type: 'POST', dataType: 'json',
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    data: {
            searchForIt: document.getElementById('searchValue').value
        },
    error: OnError,
    success: function (data) {
        // Do Stuff
    }
});

而错误函数OnError为:

function OnError(xhr, errorType, exception) {
    var responseText;
    $("#dialog").html("");

    try {
        responseText = jQuery.parseJSON(xhr.responseText);
        $("#dialog").append("<div><b>An error has occurred, please inform Paul Zahra quoting the following details:</b></div>");
        $("#dialog").append("<div><b>" + errorType + " " + exception + "</b></div>");
        $("#dialog").append("<div><u>Exception</u>:<br /><br />" + responseText.ExceptionType + "</div>");
        $("#dialog").append("<div><u>StackTrace</u>:<br /><br />" + responseText.StackTrace + "</div>");
        $("#dialog").append("<div><u>Message</u>:<br /><br />" + responseText.Message + "</div>");
    } catch (e) {
        responseText = xhr.responseText;
        $("#dialog").html(responseText);
    }
}

在控制器中如何设置 JSon 错误的参数,以便我可以提供自定义详细信息,例如“您输入了无效数据”。或“数据库有问题,请重试。”?;

OnError(xhr, errorType, exception)

附:在控制器中,为了让视图中的 ajax 认为发生了错误,我只是使用:

Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;

附言我知道以下内容,但它没有解释我如何从 mvc 控制器设置它。

"错误 类型:函数(jqXHR jqXHR,字符串 textStatus,字符串 errorThrown ) 请求失败时调用的函数。该函数接收三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生)。第二个参数(除了 null)的可能值是“timeout”、“error”、“abort”和“parsererror”。发生 HTTP 错误时,errorThrown 会接收 HTTP 状态的文本部分,例如“未找到”或“内部服务器错误”。

"为了向后兼容 XMLHttpRequest,jqXHR 对象将公开以下属性和方法:

readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()"

【问题讨论】:

    标签: c# jquery ajax json asp.net-mvc-4


    【解决方案1】:

    建议仅对意外的服务器错误使用 Ajax 调用的 'error' 事件。

    如果您想向用户显示在应用程序中并非异常的错误,例如如果输入错误或重复记录。 然后您可以在控制器中形成 Json 结果,使其具有属性“状态”和“消息”。

    然后,根据您的逻辑,在您的 Json 对象中分配 Status = Success / Error 和 Message = 'Any custom message'。并从控制器操作返回。

    然后您需要在“成功”事件中检查您的响应的状态属性。并相应地显示消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多