Graffen
Graffen

Reputation: 213

How do I return errors from my asp.net mvc controller when doing a jquery ajax post?

I'm creating a website in ASP.NET MVC and have stumbled across something I really can't figure out.

I've got a user profile page that allows a user to change his password. On the serverside, I want to validate that the user has entered a correct "current" password before allowing the change.

What's the best way to return to my View when the password isn't correct? I've tried using ModelState.AddModelError and then return Json(View()) but I can't see the error message anywhere in the JSON object returned to the browser.

What's the best way to do this using jquery on the client?

/Jesper

Upvotes: 1

Views: 237

Answers (2)

Konstantin Tarkus
Konstantin Tarkus

Reputation: 38378

I would create to classes

JsonOK : JsonResult { ... }
JsonError : JsonResult { ... }

And use those 2 for OK and Error responses.

try
{
    ...
}
catch (Exception ex)
{
    return JsonError(ex.Message);
    // or output your own message
    // or pass into it ModelState with your errors
}

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

ModelState does not automatically do anything with the returned Json. You should manually fill in a model object with data you want to return to the client.

Alternatively, if you want to report errors to the client, you can throw an exception in the controller action method and handle it in jQuery.

Upvotes: 1

Related Questions