【问题标题】:Is there any way to prevent form submit in MVC 5?有什么方法可以防止在 MVC 5 中提交表单?
【发布时间】:2016-05-04 08:15:31
【问题描述】:

我有一个发件人。

@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>
}

一切正常。我有一个不符合格式的 dropdwon。我想检查,如果选择了下拉值,则可以提交表单,否则将不会提交。简而言之,下拉选择是必需的,并且它不在表格中。我可以使用 jquery 或 javascript 检查是否选择了 dropdwon 天气的值。我的问题是如果未选择值,我如何防止提交表单?

【问题讨论】:

  • 处理表单.submit()事件并在必要时取消它。

标签: javascript jquery asp.net-mvc forms


【解决方案1】:

使用 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
      }
}

要将id 设置为您的form,请使用此重载:

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

【讨论】:

    【解决方案2】:

    我认为最正确的处理方法是使用验证http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

    使用验证属性标记与下拉列表绑定的模型字段。 这种方法的优点 - 您可以通过调用ModelState.IsValid 在服务器端进行验证。即使 javascript 将被禁用,服务器验证也将起作用。

    【讨论】:

    • OP 已声明下拉列表不是在表单中
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多