Click here to Skip to main content
15,907,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am binding a dropdown using Entitiyframework and i want to validate if the value is selected or not on a button click

public class DeviceModel
       [Required(ErrorMessage = "Select a value")]
       public SelectList DeviceListModel { get; set; }

       [Required(ErrorMessage = "Select a value")]
       public SelectList DeviceType { get; set; }


public ActionResult Index()
          List<Example> mod = (from data in obj.Examples select data).ToList();
          Example exp = new Example();
          exp.Name = "--Select--";
          exp.ID = 0;
          mod.Insert(0, exp);
          SelectList modeldata = new SelectList(mod, "ID", "Name", 0);
          DeviceModel objmodel = new DeviceModel();
          objmodel.DeviceListModel = modeldata;
          List<Gearhead_Type> types = (from data in obj.Gearhead_Type select data).ToList();
          Gearhead_Type GTypre = new Gearhead_Type();
          GTypre.Name = "--Select--";
          GTypre.ID = 0;
          types.Insert(0, GTypre);
          SelectList asd = new SelectList(types, "ID", "Name", 0);
          objmodel.DeviceType = asd;

          return View(objmodel);


<div class="form-group">
               @Html.Label("Gearhead Model and Type  ", new { @class = "col-md-6 control-label ", @style = "padding-left:200px" })
               @Html.DropDownListFor(s=>s.DeviceListModel,  Model.DeviceListModel)
               @Html.ValidationMessageFor(s => s.DeviceListModel)

But the validation is not working in the button click.

Share this answer
You need to check if the model is valid in your action and if it isn't return the same view and model so the error messages can be shown.[^]

If you want client-side validation also then google " mvc unobtrusive client-side validation" and you'll find walkthroughs on how to enable it.
Share this answer
you Add On Your Page

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900