views:

115

answers:

2

Hi!

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

+1  A: 

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.

Mehrdad Afshari
+2  A: 

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
}
Koistya Navin