ASP.Net MVC 5 Html.BeginForm onsubmit and model with required attribute

天大地大妈咪最大 提交于 2019-12-13 21:34:57

问题


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
   }
});


来源:https://stackoverflow.com/questions/43094034/asp-net-mvc-5-html-beginform-onsubmit-and-model-with-required-attribute

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