I've been looking for answers on how to add an HTML class tag on my html.dropdownlist. here is the code
<%: Html.DropDownList("PackageId", new SelectList(ViewData["Packages"] as IEnumerable, "PackageId", "Name", Model.PackageId))%>
I want to add classes for options under the select element so that I can use this chained select :
<select id="category">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="package">
<option value="1" class="1">One - package1</option>
<option value="2" class="1">One - package2</option>
<option value="3" class="2">Two - package1</option>
<option value="4" class="2">Two - package2</option>
</select>
$("#series").chained("#mark");
I've done this for the DropDownlistFor extension method, not the DropDownList you use, but you can probably figure that out yourself. This stuff is mostly copy/paste from the MVC sources. You can find the sources here.
I wrote a wrapper that simply modifies the html:
and then I wrapped my DropDownListFor with this helper function:
You could obviously make the helper function more sophisticated if you want.
First thing that comes to my mind is JQuery here. You can do this with following code easily :
This is not possible with the DropDownList helper that is built into ASP.NET MVC. As a consequence you will have to write your own helper if you need to do that. You could take a look at the source code of ASP.NET MVC which uses TagBuilder to generate the options and you could append any attributes in your custom implementation. Another less elegant solution is to manually loop through the dataset in the view and generate individual option elements.
Here's a little improved version of @john-landheer's solution.
Things improved:
GetModelStateValue()
fixedDropDownList()
extension method addedunobtrusive validation attributes will be rendered just like they should