Search code examples
asp.net-mvcerror-handlingmodelstate

How to read modelstate errors when returned by Json?


How can I display ModelState errors returned by JSON?

I want to do something like this:

 if (!ValidateLogOn(Name, currentPassword))
    {
        ModelState.AddModelError("_FORM", "Username or password is incorrect.");

        //Return a json object to the javascript
        return Json(new { ModelState });
    }

What must be my code in the view to read the ModelState errors and display them?

My actual code in the view to read the JSON values is as follows:

function createCategoryComplete(e) { 
    var obj = e.get_object(); 
    alert(obj.Values); 
} 

Solution

  • If you are returning JSON, you cannot use ModelState. Everything that the view needs should be contained inside the JSON string. So instead of adding the error to the ModelState you could add it to the model you are serializing:

    public ActionResult Index()
    {
        return Json(new 
        {
            errorControl = "_FORM",
            errorMessage = "Username or password is incorrect.",
            someOtherProperty = "some other value"
        });
    }