最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there any way to prevent form submit in MVC 5? - Stack Overflow

programmeradmin5浏览0评论

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. 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. My question is how i prevent to submit the form if value is not selected?

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. 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. My question is how i prevent to submit the form if value is not selected?

Share Improve this question asked May 4, 2016 at 8:15 CodeLoverCodeLover 2811 gold badge4 silver badges14 bronze badges 1
  • 1 Handle the forms .submit() event and cancel it if necessary. – user3559349 Commented May 4, 2016 at 8:17
Add a ment  | 

2 Answers 2

Reset to default 12

With jQuery it's simple:

$("#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:

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/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. Server validation will work even if javascript will be disabled.

发布评论

评论列表(0)

  1. 暂无评论