Search code examples
javascriptasp.net-mvcmodelstate

asp.net MVC form validation in javascript


I have a page with an ajax form on it. When I press the submit it should load some loading gif. See the following HTML and javascript:

@using (Ajax.BeginForm("ActionName", "ControllerName", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DivToUpdate" }, new { id = "myForm" })) { @Html.AntiForgeryToken();

@Html.LabelFor(model => model.PagerSize)
    @Html.EditorFor(model => model.PagerSize, new { htmlAttributes = new { @class = "form-control myForm", style = "width:100px" } })
    @Html.ValidationMessageFor(model => model.PagerSize)

<input id = "ajaxFormSubmitButton" type = "submit" />
}

<script>
$("#myForm").submit(function (event) {

           DisplayLoading();

       });

</script>

It works fine until my model is not valid. For example when I have a pagersize outside my range, it keeps on showing my loading gif as the page doesn't load anything else. Is it possible to only load the DisplayLoading when my ModelState.IsValid?

For example something like this:

<script>
$("#myForm").submit(function (event) {
If (MyMagicVariableWhichKnowsMyModelStateIsValid){
           DisplayLoading();
}
       });

</script>

Solution

  • You can check form is valid as below:

    $("#myForm").submit(function (event) {
    if ($("#myForm").valid()){
           DisplayLoading();
    }
    });