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

标签 javascript jquery asp.net-mvc-2 jquery-validate http-post

我有 2 个问题,在第一个问题中,我得到一个列表,我想 C# 代码( Controller )中的 excetpion 是否可以查看(错误 View )并将其显示在特定的 div 中。如何在 .error 中获取 View 。 ? HTML

<div><a href="#" class="MnuCustomerList">List</a></div>

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"); });
})

;

Controller :

public PartialViewResult List()
{
    throw new Exception("myexception");
    return PartialView("List");
}

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

@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>
}

在 Controller 中,我检查代码是否已经存在,如果是,CustomerException("Code exist")。

我的问题是,是否可以使用 jQuery 发布此表单,但仍然使用模型中的这种格式,而不是像下面的示例那样一个值一个值地获取一个值

$.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) { }
});

谢谢,

最佳答案

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

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

Controller Action :

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

Javascript:

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

关于javascript - 使用 jquery 在 ASP.NET MVC 中进行异常管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5586637/

相关文章:

asp.net - 用于验证的数据注释,至少一个必填字段?

javascript - 如何查找除了两小时前更新的文档之外的文档?

javascript - 如何不断更新我正在使用JS播放的mp3文件的持续时间?进度栏不起作用

javascript - 如何验证仅通过 JavaScript 正则表达式输入的字母和空格

javascript indexOf - 列表/数组中的完全匹配

javascript - 定义 Kendo UI 默认值和功能

c# - ASP.NET MVC Html.ActionLink 维护路由值

c# - ADO.Net:在解决方案中的多个项目之间共享实体 (.edmx)

javascript - Google map 信息窗口在 map 外部单击时打开

javascript - 是否可以在主显示器以外的其他显示器上显示网络推送通知?