Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 SelectListItem. Is it possible to decorate it with custom html attributes?

if I have something like this:

@{
   var cats = GetCategories();
   var selectList = from c in cats
   select new SelectListItem
   {
     Selected = (c.Id == Model.SessionCategory.Id),
     Text = c.Name,
     Value = c.Id.ToString(),
    };
  }
 @Html.DropDownList("categories", selectList)

The markup would be like this:

 <select id="categories" name="categories">
    <option value="1">Category1</option>
    <option value="2">Category2</option>
    <option selected="selected" value="3">Category3</option>
 </select>

And now, the question is:

Is it possible to add additional attributes to each <option> tag? I mean from the Razor template. Without jQuery workarounds?

like image 941
iLemming Avatar asked Feb 25 '23 14:02

iLemming


1 Answers

I think the most practical solution would be some jQuery or maybe something like this..

<select id="categories" name="categories">
    @foreach (var item in selectList) {
        <option @if (item.Selected) { <text>selected="selected"</text>} value="@item.Value">@item.Text</option>
    }
</select>

you could obviously add in attributes as needed...

like image 122
Justin Soliz Avatar answered Mar 09 '23 01:03

Justin Soliz