使用jquery在ASP.NET MVC中进行异常管理

Kri*_*s-I 1 javascript jquery http-post jquery-validate asp.net-mvc-2

我有2个问题,在第一个问题中,我得到一个列表,我想如果C#代码(控制器)中的例外情况有可能出现一个View(一个错误视图)并显示一个特定的div.如何在.error中获取视图.?HTML

<div><a href="#" class="MnuCustomerList">List</a></div>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(".MnuCustomerList").click(function () {
    var jqxhr = $.post("/Customer/List", function (data) {
        $('#rightcolumn').html(data);
    })
    .success(function () { alert("success"); })
    .error(function () { alert("error"); })
    .complete(function () { alert("complete"); });
})
Run Code Online (Sandbox Code Playgroud)

;

控制器:

public PartialViewResult List()
{
    throw new Exception("myexception");
    return PartialView("List");
}
Run Code Online (Sandbox Code Playgroud)

第二个问题:我有一个表格

@model MyModel
@using (Html.BeginForm("Save", "Customer", FormMethod.Post))
{
    <table style="width:100%;">
    <tr>
        <td>Code</td>
        <td>@Html.TextBoxFor(m => m.Customer.Code, new { id = "tbCode" })</td>
    </tr>
    <tr>
        <td>LastName</td>
        <td>@Html.TextBoxFor(m => m.Customer.LastName, new { id = "tb", maxlength = 50, style = "width:40%;" })</td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="A submit button"/></td>
    </tr>
    </table>
}
Run Code Online (Sandbox Code Playgroud)

在Controller中,我检查代码是否已经存在,如果是,则为CustomerException("代码存在").

我的问题是,是否可以使用jQuery BUT发布此表单仍然使用这个模型的意思,而不是像下面的示例一样获得一个值

$.ajax({
    type: "POST",
    url: "/Customer/Save",
    data: {
        id: $('#Id').val(),
        firstName: $('#FirstName').val(),
        lastName: $('#LastName').val(),
        isEnable: $('#IsEnable').attr('checked')        
    },
    success: function (html) {
        $("#ContentDataSection").html(html);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
Run Code Online (Sandbox Code Playgroud)

谢谢,

Cra*_*g M 6

如果在发出ajax请求时出错,则只会触发错误回调.如果服务器端发生错误,您需要将数据传回(以Json格式将是一个不错的选择)到客户端,指示服务器端出现故障并在成功回调中处理它.

编辑以添加代码,显示如何将响应代码设置为500,以便根据Ryan的评论在错误回调中处理:

控制器动作:

public ActionResult FiveHundred()
{
    Response.StatusCode = 500;
    return Json(new {Error = "Uh oh!"});
}
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

$.ajax({
    url: "/home/fivehundred",
    type: "POST",
    success: function(data) {
        // handle normally
    },
    error: function(data) {
        alert("error " + data.Error);
    }
});
Run Code Online (Sandbox Code Playgroud)