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!
No, there is nothing special to do. There is propably something wrong with your posting logic. Instead of setting posted values by hand, try using jQuery Form Plugin. it makes ajax posting easier and helps to get rid of weird errors.
I just prepared simple example and it worked fine (it used jQuery form) (EDIT: $.post(‘/Login/Test3’, { AAA: $(‘#AAA’).val() }); worked fine too):
Controller:
View: