在控制器中设置ajax / JSon错误详细信息

时间:2015-03-20 12:22:47

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

如果我在观点中有以下内容:

$.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)

P.S。在控制器中,为了在视图中获取ajax以认为发生了错误,我只使用:

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

P.P.S。我知道以下内容,但它没有解释我是如何从mvc控制器设置的。

“的错误 类型:函数(jqXHR jqXHR,String textStatus,String 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()"

1 个答案:

答案 0 :(得分:1)

建议使用&#39;错误&#39; Ajax事件只调用意外的服务器错误。

如果您想向用户显示错误,这在应用程序中不是例外,例如如果输入错误或重复记录。 然后,您可以在控制器中形成Json结果,以获得属性&#39;状态&#39;和&#39;消息&#39;。

然后,根据您的逻辑,分配Status = Success / Error,Message =&#39;任何自定义消息&#39;在你的Json对象中。并从控制器动作返回。

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

相关问题