简体   繁体   English

如何使用MVC验证带有客户端验证的dropdownlist元素?

[英]How to validate a dropdownlist element with client side validation using MVC?

I would like to implement client side validation for a drop down list. 我想为下拉列表实现客户端验证。

Model 

public partial class Beach
    {
        public int Beach_ID{ get; set; }
        [Required]
        public string NAME { get; set; }

        [Required]
        public Nullable<int> LOCATION_ID { get; set; }


        public virtual LOCATION LOCATION { get; set; }
    }

Controller

 public ActionResult Edit(int? id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BEACH BEACH  = db.BEACH .Find(id);
            if (BEACH  == null)
            {
                return HttpNotFound();
            }
             ViewBag.LOCATION = new SelectList(db.LOCATION, "LOCATION_ID", "LOCATION_NAME", BEACH.LOCATION_ID);
            return View(BEACH);
        }

View

 <div class="form-group">
            <div class="col-md-10">
                @Html.DropDownList("LOCATION", null, "Select Location", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.LOCATION_ID, "", new { @class = "text-danger" })
            </div>
        </div>


The name field is required and if the form is submitted with it being blank, the client side validation works fine. 名称字段是必填字段,如果表单提交为空白,则客户端验证工作正常。 However, the dropdown list only works with server side validation. 但是,下拉列表仅适用于服务器端验证。

You could use JQuery to validate on Button click. 你可以使用JQuery来验证按钮点击。

You could add an id to your DropDownList in the following way 您可以通过以下方式向DropDownList添加ID

  @Html.DropDownList("LOCATION", null, "Select Location", htmlAttributes: new {  @id="dropdownid",@class = "form-control" })

And write the following code in the script tag. 并在脚本标记中编写以下代码。

 $('#Submit').click(function(){
    var ddlvalue= $("#dropdownid option:selected").val();
    if(ddlvalue!='-1')
    {    
      //Do your work.
    }
  else
  alert('Please select Location");
   });

asp.net mvc jquery dropdown validation asp.net mvc jquery下拉列表验证

You can refer above link it may help to figure out your problem. 你可以参考上面的链接,它可能有助于找出你的问题。

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

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