How know if ModelState contains errors

前端 未结 3 758
生来不讨喜
生来不讨喜 2021-02-14 08:32

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 <

相关标签:
3条回答
  • 2021-02-14 08:57

    In addition to Darins Answer:

    In .cshtml:

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

    in JS

    var isValid = $('#IsValid').val().toLowerCase() == "true";
    
    0 讨论(0)
  • 2021-02-14 09:06

    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.

    0 讨论(0)
  • 2021-02-14 09:08

    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');
        }
    });
    
    0 讨论(0)
提交回复
热议问题