ModelState.IsValid always true when accessed on View

人走茶凉 提交于 2021-02-08 10:11:18

问题


By following this i got the ModelState.IsValid ins jquery code. but it is always true, i can see the error on my page. What i am trying to achieve is show loading when a form is submitted. I used onclick event of submit. It shows loading even if there are validation errors on page. I don't wanna show loading in this case. I also tried using Form's Submit event but same results.

My ViewModel is having DataAnnotations for validations and form is in a partial view. Any suggestions how can i achieve this loading message successfully ?

This is my form

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "frmFlightSearch", onsubmit = "CheckModalErros()" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(false)
......
<div class="row" style="margin-bottom:10px;margin-top:10px;">
    <div class="col-lg-3 pull-right">
        <div class="form-group-sm">
            <button id="btnSubmit" type="submit" class="btn btn-sm btn-primary pull-right">
                Search Flights
                <span class="glyphicon glyphicon-plane"></span>
            </button>
        </div>
    </div>
</div>
}

回答1:


It shows loading even if there are validation errors on page. I don't want show loading in this case.

Add this event handler:

$("#frmFlightSearch").bind("invalid-form.validate", function () {
    // hide 'loading' 
});

this will trigger when your client-side validation fails and you can hide the whatever it is that you're showing for 'loading' progress.

If client-side validation fails, then it won't post anyway (using asp.net mvc + jquery validation).




回答2:


If you are loading your form using partial view using an ajax call, in success callback do something like below:

$.ajax({
     success: function(data){
                 $('#DivId').html(data);
                 $.validator.unobtrusive.parse($("#FormId"));
             }
});

This will parse your form's validation and your form will show validation message when you click on submit and if model is not valid.

Hope this help.

Edit:

As you said on click you need to check below line of code:

if($('#FormId).Valid())
{
   $('#Loader').show(); //show loader if form is valid.
}
else
{
   e.preventDefault(); // prevent default event if form is not valid.
}


来源:https://stackoverflow.com/questions/30596917/modelstate-isvalid-always-true-when-accessed-on-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!