简体   繁体   English

有没有办法阻止MVC 5中的表单提交?

[英]Is there any way to prevent form submit in MVC 5?

I have a from. 我有一个来自。

@using (Html.BeginForm())
{
 // From content 
 <div class="form-group btn-group">
                <button type="submit" class="btnPrimaryStyle btn  col-sm-3 col-xs-12 pull-left">Save</button>
            </div>
}

Everything is working fine. 一切都很好。 I have a dropdwon which is out of the form. 我有一个不在形式的dropdwon。 I want to check, if dropdown value is selected,then form can be submitted otherwise it will not submit. 我想检查一下,如果选择了下拉值,则可以提交表单,否则将不提交。 In short, the dropdown selection is required and it is out of the form. 简而言之,下拉选项是必需的,它不在形式中。 I can check the value of dropdwon weather it is selected or not with jquery or javascript. 我可以使用jquery或javascript检查dropdwon天气的值是否被选中。 My question is how i prevent to submit the form if value is not selected? 我的问题是,如果未选择值,我如何阻止提交表单?

With jQuery it's simple: 使用jQuery很简单:

$("#your-form-id").submit(function (e) { // note that it's better to use form Id to select form
      if($("#YourDropDownID").val() == 0 || $("#YourDropDownID").val() == '') // here you check your drop down selected value
      {
         e.preventDefault(); // here you stop submitting form
      }
}

To set id to your form use this overload: 要为form设置id ,请使用以下重载:

Html.BeginForm(null, null, FormMethod.Post, new { id = "your_form_id" })

I think the most correct way to handle this is to use validation http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation 我认为最合适的方法是使用验证http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

Mark the field of your model that bound with dropdown list with validation attribute. 使用验证属性标记与下拉列表绑定的模型字段。 The advantage of this method - you can validate on server side by calling ModelState.IsValid . 此方法的优点 - 您可以通过调用ModelState.IsValid在服务器端进行验证。 Server validation will work even if javascript will be disabled. 即使将禁用javascript,服务器验证也会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM