Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How know if ModelState contains errors

When a form is posted in my controller, I make the following check:

if(ModelState.IsValid)

If the model is not valid, errors are added to the ModelState. The model is then passed to the view with validation summary.

However, I want to check if the ModelState has errors from inside the jQuery ready handler, so that I can add some additional behavior if the form has errors. Is that possible?

like image 698
John x Avatar asked Jan 18 '12 09:01

John x


3 Answers

You could spit global javascript variable:

<script type="text/javascript">
    var isValid = @Html.Raw(Json.Encode(ViewData.ModelState.IsValid));
</script>

and then:

$(function() {
    if (!isValid) {
        alert('opa');
    }
});
like image 178
Darin Dimitrov Avatar answered Sep 28 '22 06:09

Darin Dimitrov


a little addition to @Dimitrov answer:

<script type="text/javascript">
    var isValid = '@Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';

    if (isValid != 'true')
        // model has some errors...
</script>

It's important to use single qoutes around the helper. Otherwise, that ending semicolon ; cause problems. Nether you can write it, nor you can't, at all cases it cause a syntax error. Unless you put those single quotes around the helper as I mentioned.

like image 32
Amin Saqi Avatar answered Sep 28 '22 05:09

Amin Saqi


In addition to Darins Answer:

In .cshtml:

@Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))

in JS

var isValid = $('#IsValid').val().toLowerCase() == "true";
like image 43
raklos Avatar answered Sep 28 '22 06:09

raklos