jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery验证,ASP.NET MVC ModelState错误(异步POST)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用asp.net mvc 3开发一个Web应用程序,并且我有一些形式,POST到异步动作(通过ajaX)。此操作会使用一些数据注释来查看viewmodel,以验证它。验证工作正常,但是当验证器返回错误时,我不知道如何在我的视图中返回它显示(因为POST是由ajax创建的)。

我的行动是这样的

[httpPost]
public ActionResult SaveCustomer(Customerviewmodel input) {
    if (!ModelState.IsValid) { // <-- business validation
        return Json(new { success = false,errors = ???});
    }
    // persist 
    return Json(new { success = true });
}

在我看来,如何用jquery验证这个错误
如果可以发布一些代码进行抽样…我会加以虑!

多谢你们!

解决方法

在发生错误的情况下,我不会发送JSON,而是将表单放在部分中,然后控制器操作会在出现错误的情况下返回此部分。 JSON的问题是,事实上,您可以使用LINQ从ModelState中获取错误,但它可能是PITA在视图上显示它们。

所以:

<div id="myform">
    @Html.Partial("_MyForm")
</div>

然后在_MyForm.cshtml里面:

@model Customerviewmodel
@using (Html.beginForm())
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationmessageFor(x => x.Foo)
    <br />
    @Html.EditorFor(x => x.bar)
    @Html.ValidationmessageFor(x => x.bar)
    <br />
    <input type="submit" value="OK" />
}

并且控制器动作将成为:

[httpPost]
public ActionResult SaveCustomer(Customerviewmodel model)
{
    if (!ModelState.IsValid)
    {
        return PartialView("_MyForm",model);
    }
    return Json(new { success = true });
}

最后一步是AJAXify这个表单可以在一个单独的javascript文件中完成:

$(function () {
    $('#myform').delegate('form','submit',function () {
        $.ajax({
            url: this.action,type: this.method,data: $(this).serialize(),success: function (result) {
                if (result.success) { 
                    // We have a JSON object in case of success
                    alert('success');
                } else {
                    // We have the partial with errors in case of failure
                    // so all we have to do is update the DOM
                    $('#myform').html(result);
                }
            }
        });
        return false;
    });
});

大佬总结

以上是大佬教程为你收集整理的jQuery验证,ASP.NET MVC ModelState错误(异步POST)全部内容,希望文章能够帮你解决jQuery验证,ASP.NET MVC ModelState错误(异步POST)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。