C# ASPNET MVC - How do you use ModelState.IsValid in a jquery/ajax postback?

Posted by JK on Stack Overflow See other posts from Stack Overflow or by JK
Published on 2010-05-02T22:13:20Z Indexed on 2010/05/02 22:18 UTC
Read the original article Hit count: 479

From what I've seen ModelState.IsValid is only calculated by the MVC frame work on a full postback, is that true?

I have a jquery postback like so:

var url = "/path/to/controller/myaction";
var id = $("#Id").val();
var somedata = $("#somedata").val();  // repeated for every textbox
$.post(url, { id: id, somedata: somedata },
function (data) {
  // etc
});

And the controller action looks like:

public JsonResult MyAction(MyModel modelInstance) 
{
    if (ModelState.IsValid)
    {
        // ... ModelState.IsValid is always true, even when there is invalid data
    }
}

But this does not seem to trigger ModelState.IsValid. For example if somedata is 5 characters long, but the DataAnnotation says [StringLength(3)] - in this case ModelStae.IsValid is still true, because it hasn't been triggered.

Is there something special I need to do when making a jquery/ajax post instead of a full post?

Thanks!

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about dataannotations