ASP.Net MVC 5 Html.BeginForm onsubmit and model wi

2019-09-14 20:39发布

问题:

I have required attribute on my model properties but I added a "spinner" to show processing request in form onsubmit. Now, even though that it didn't submit the form, it shows the "spinner" i created, and stuck on the overlay but the textbox with required attribute is in focus.

using (Html.BeginForm("Add", "UserAccount", FormMethod.Post, new { onsubmit="spinner()"}))
{
//Html.TextBoxes for model properties with required
}
<div id="spinner" hidden="">
    <div>
        <i class="fa fa-spinner fa-spin fa-pulse" style="color: white; font-    size: 50px;"></i>
        <label style="color: white; font-size: 50px;">Processing</label>
    </div>
</div>




<script>
function spinner() {
    $("#spinner").show();
}
</script>

Is their a way to check first if the "required" attribute is satisfied before accessing the onsubmit function?

回答1:

You need to add submitHandler function to validator. Here is the complete code.

<script type="text/javascript">
   $(function () {

      $("form").data("validator").settings.submitHandler = function (form) {
         $("#submit-button").html("<i class=\"fa fa-spinner fa-pulse\"></i> Signing In...")
            .prop('disabled', true);
         form.submit();
      };
   });
</script>


回答2:

I think you need client side validation before form has been submitted you have added required attribute on properties that is fine now make a client side validation work you need to add some js which is handle all validations client side

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));

Below is list of js you need

<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

You need jquery.validate.unobstrusive.js to make client validation work

Second you need to change in web config as well

 <appSettings>  
        ...
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 

        ...
 </appSettings>

Fore more infomration find what is unobtrusive-validation on this blog.

Using this your form is not submitted before all fields are validated properly like Required,Range etc which you have mentioned on properties

After adding this bunch of code you can validate form in on button click as well as below

$("#btn1").click(function (e) {

   e.preventDefault();

   // now trigger the form validation, result is 1 or 0
   var result = $('form').valid();  
   if(!result)
   {
     // Do some stuff if form is not valid
   }
});