1

I am building a dropdownlist using the answer here: SelectListItem with data-attributes. This will allow me to add a different class and data annotations to different <option>'s

However I am struggling with building the <select> initially. I have

<select name="@Html.NameFor(a=>a.ValueType)"
            id="@Html.IdFor(a=>a.ValueType)">
</select>

My ViewModel looks like

 [Required(ErrorMessage = "Value Type is required")]
 public string ValueType { get; set; }

How do I get the Required annotation validation into the view?

The final html in the browser should look like:

 <select id="ValueType" name="ValueType" data-val-required="Value Type is required" data-val="true"></select>

but I currently have:

<select id="ValueType" name="ValueType"></select>

Is there a @Html method to get these data-val from the ViewModel attributes or how do i do this? Do I have to hard-code it?

Community
  • 1
  • 1
k29
  • 641
  • 6
  • 26
  • You have to hard code it, but you mentioned adding class names to the options. You have almost no control over how options are rendered (its done by the browser/OS) so not sure how much value class names will be. –  Mar 04 '15 at 08:12
  • Well the goal is to somehow attach a javascript event to a subset of the options. My solution was to add a class to certain options. It's not for visual/rendering purposes – k29 Mar 04 '15 at 08:14
  • An option might be to pass a List to the view (view model or `ViewBag` property) containing the "class names", (one per option) and using jquery to then add the class name to the options. That would at least mean you could use he html helpers. Manually adding the validation attributes is a bit fragile - what if you changed an attribute later - could be difficult to debug? –  Mar 04 '15 at 09:18
  • That's a good idea. Thanks. I'm also looking at the possibility of passing the subset of options in a different List, hiddenfor'ing each item, and using jquery on document ready to assign the classes by comparing to them – k29 Mar 04 '15 at 09:28

0 Answers0