ASP Net 4如何将错误对象传递给JSON [英] ASP net 4 how pass the errors objects to a json

查看:96
本文介绍了ASP Net 4如何将错误对象传递给JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将我的ModelState错误传递给json,并在jquery中将表单中的对象关联.我的表格:

How I pass my ModelState errors to json and in jquery associate a object in the form. My form:

<form id="form">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                @Html.TextBoxFor(m => m.VatNumber,new { @class = "form-control", @id="VatNumber"})
                 @Html.ValidationMessageFor(model => model.VatNumber, "", new { @class = "text-danger" })
             </div>
        </div>
        <div class="col-sm-6">
             <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Check VAT" />
            </div>
        </div>
   </div>
</form>

我的控制器:

   [HttpPost]
    public ActionResult CheckVat(VatSearch data)
    {
        //string a =vatnumber.VatNumber;
        //return Json(data.VatNumber);
        return Json(ModelState);
    }

他给出了一个错误:

检测到循环引用使序列化序列无效 对象类型

It was detected a circular reference to void the serializade an object type

推荐答案

您的代码实际上没有任何意义.为什么要返回ModelState词典?如果您尝试使用模型验证,则还有其他几种方法可以做到这一点.

Your code actually does not makes sense. Why would you want to return ModelState dictionary ? If you are trying to make use of the Model validation, you have several other ways to do that.

如果模型验证失败,则可以将验证错误消息作为json响应的一部分返回,并根据需要向用户显示

If Model validation fails, you can return the validation error messages as part of your json response and show that to the user as needed

[System.Web.Mvc.HttpPost]
public ActionResult CheckVat(VatSearch data)
{
    var list = new List<string>();
    if (!ModelState.IsValid)
    {
        var errors = ViewData.ModelState.Values
                             .SelectMany(f => f.Errors
                                              .Select(x => new {Error = x.ErrorMessage,
                                                      Exception =x.Exception})).ToList();
        return Json(new {Status="error",Errors = errors});

    }
    return Json(new {Status="success"});
}

在您的ajax调用的成功方法中,只需检查Status属性,然后检查它是否为"error",遍历Errors集合并获取每个错误并根据需要使用.

and in your ajax call's success method, simply check the Status property and then if it is "error", loop through the Errors collection and get each errors and use as needed.

success: function (result) {
    if(result.Status==="error")
    $.each(result.Errors, function(a, b) {
            alert(b.Error);
    });
},

您应该认真考虑的另一件事是使用客户端非侵入式验证.甚至在您提交表单之前,都会进行客户端验证.

Another thing you should seriously consider is using the client side unobtrusive validation. This does the client side validation even before you submit the form.

这篇关于ASP Net 4如何将错误对象传递给JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆