0

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>

My controller:

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

He gives a error:

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

1 Answer 1

0

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.

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

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If i do that the valisation gives always sussecceful and i use unobtrusive validation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.