SelectListItem with data attributes

Is there anyway for the SelectList to be pre-added to the ViewModel with data attributes?

I want to do

@Html.DropdownListFor(m=> m.CityId, Model.Cities); 

therefore, it generates code like:

 <select id="City" class="location_city_input" name="City"> <option data-geo-lat="-32.522779" data-geo-lng="-55.765835" data-geo-zoom="6" /> <option data-geo-lat="-34.883611" data-geo-lng="-56.181944" data-geo-zoom="13" data-geo-name="Montevideo" data-child=".state1" value="1">Montevideo</option> <option data-geo-lat="-34.816667" data-geo-lng="-55.95" data-geo-zoom="13" data-geo-name="Canelones, Ciudad de la Costa" data-child=".state41" value="41">Ciudad de la Costa</option> </select> 
+53
html5 asp.net-mvc html-helper custom-data-attribute
Jul 15 '13 at 23:09
source share
2 answers

Here is a simple solution.

Not everything needs to be written using the extension method in .NET code. One of the great features of MVC is its easy access to create your own HTML.

With MVC4, you can get the identifier and name of an element in the expression tree using the HTML.NameFor and HTML.IdFor

 <select name="@Html.NameFor(Function(model) model.CityId)" id="@Html.IdFor(Function(model) model.CityId)" class="location_city_input"> @For Each city In Model.Cities @<option value="@city.Value" @(If(city.Value = Model.CityId, "selected", "")) data-geo-lat="@city.Lat" data-geo-lng="@city.Lng" data-geo-zoom="@city.Zoom"> @city.Text </option> Next </select> 

Assuming Model.Cities is a collection of elements that expose each of these properties. Then you must be tuned.

If you want reuse, consider making it an editor template for everything that is enumerable from cities

+80
Dec 31 '15 at 20:00
source share

You will need to extend SelectListItem and then extend DropDownListFor to use the extended SelectListItem.

Take a look at this solution:

Adding an html class tag under <option> to an Html.DropDownList

+9
Jul 16 '13 at 1:41
source share



All Articles