I\'ve been playing with the new MVC3 Json Model Binding and it\'s quite nice.
Currently, I can post JSON to controller and bind it. Model Validation occurs nicely too.>
The following example works for me when using unobtrusive JavaScript in MVC3. I'm doing something very similar. Given the following JsonResponse
class:
public enum Status
{
Ok,
Error
}
public class JsonResponse
{
public Status Status { get; set; }
public string Message { get; set; }
public List Errors { get; set; }
}
My controller can have a method thus:
[HttpPost]
public ActionResult Login(UserLoginModel model)
{
JsonResponse res = new JsonResponse();
if (!ModelState.IsValid)
{
res.Status = Status.Error;
res.Errors = GetModelStateErrorsAsString(this.ModelState);
res.Message = "Oh dear, what have you done. Check the list of errors dude!";
}
else
{
// Save it here...
// Return success
res.Status = Status.Ok;
res.Message = "Everything was hunky dory";
}
return Json(res);
}
And the ModelStateDictionary can be enumerated for the errors as so:
private List GetModelStateErrorsAsString(ModelStateDictionary state)
{
List errors = new List();
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errors.Add(error.ErrorMessage);
}
}
return errors;
}
Then in my view I can have the following JSON POST:
I'm using jQuery.tmpl
to display the errors. I have excluded that from this example though.