0

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.

2 Answers 2

0

You could use JQuery to validate on Button click.

You could add an id to your DropDownList in the following way

  @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");
   });
Sign up to request clarification or add additional context in comments.

Comments

0

asp.net mvc jquery dropdown validation

You can refer above link it may help to figure out your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.