views:

437

answers:

2

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!

+1  A: 

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:

public class Test3ViewModel
{
    [StringLength(3)]
    public string AAA { get; set; }
}

[HttpPost]
public int Test3(Test3ViewModel model)
{
    if (ModelState.IsValid)
    {
        return 1;
    }
    return 2;
}

View:

<form method="post" action="/Login/Test3" id="form_test3">
    <%= Html.TextBox( "AAA" ) %>
<input type="submit" value="OK" />
</form>

<script type="text/javascript">
    $(document).ready(
        function() {
            $('#form_test3').ajaxForm(function() {
                alert("Post works fine:)");
            });
        }
    );
</script>
LukLed
I've compared your sample to see what might be wrong but haven't found the problem. My code did have different urls for the form action and the $.post url - but making them the same made no difference.
JK
One possible difference: I am not posting back all of the model fields. Some of the fields are nullable and are not being updated in this method, so they are not posted back. Do you think that would make a difference?
JK
Another thing I noticed: in my controller action, the model object is correctly populated with the data that was posted. But ModelState is empty (.count = 0).
JK
@JK: Maybe there is something in your project that messes with ModelState. Maybe some redirection that loses ModelState values. I don't know. You can create new project and check if it works there. If it works, you have to look into your code and find problem, because it is not connected to framework.
LukLed