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.
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");
});
asp.net mvc jquery dropdown validation
You can refer above link it may help to figure out your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.