ASP Net 4如何将错误对象传递给JSON

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.