Click here to Skip to main content
15,949,741 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

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

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

   }


C#
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);

      }


HTML
<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)
           </div>


But the validation is not working in the button click.
Posted

 
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.

http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model[^]

If you want client-side validation also then google "asp.net 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
 
v2

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