ASP.Net MVC 5 Html.BeginForm onsubmit和具有必需属性的模型 [英] ASP.Net MVC 5 Html.BeginForm onsubmit and model with required attribute

查看:166
本文介绍了ASP.Net MVC 5 Html.BeginForm onsubmit和具有必需属性的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型属性上具有必填属性,但是我添加了一个"spinner"以按onsubmit形式显示处理请求.现在,即使它没有提交表单,它也会显示我创建的旋转器",并粘贴在叠加层上,但是具有必填属性的文本框已成为焦点.

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>

在访问onsubmit函数之前,是否可以先检查"required"属性是否得到满足?

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

推荐答案

我认为您需要在提交表单之前进行客户端验证,并且已经在属性上添加了必填属性,现在可以进行客户端验证工作了一些处理所有验证客户端的js

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*"));

下面是您需要的js列表

Below is list of js you need

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

您需要jquery.validate.unobstrusive.js才能进行客户端验证

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

第二,您还需要更改Web配置

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.

使用此方法,您必须在属性中提到的所有字段(如RequiredRange等)都经过正确验证之前,才能提交表单

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

这篇关于ASP.Net MVC 5 Html.BeginForm onsubmit和具有必需属性的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆