Custom HTML attributes in SelectListItems in MVC2?

I need to add custom HTML attributes, in particular classes or styles, to option tags in selections generated with Html.DropDownFor ().

I played with this, and for life I can’t understand what I need to do to get what I need.

Assuming I have a list of colors for which I am creating a drop-down list where the parameter value is the color identifier and the text is the name ... this is what I would like to see as output:

<select name="Color">
   <option value="1" style="background:#ff0000">Red</option>
   <option value="2" style="background:#00ff00">Green</option>
   <option value="3" style="background:#0000ff">Blue</option>
   <!-- more here -->
   <option value="25" style="background:#f00f00">Foo Foo</option>
</select
<P →
+3
source share
2 answers

As a result, I created my own editor template.

.ascx /Views/Shared/Editors "ColorSelect.ascx"

.ascx :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64>" %>
<%var colors = ViewData["Colors"] as ColorTable;
  var name = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(String.Empty);
  var id = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty);
%>
  <select name="<%=name %>" id="<%=id %>">
  <%foreach(var color in colors) {%>
    <option value="<%=color.Id %>" style="background:<%=color.Hex%>;"<%if(color.Id == Model) { %> selected="selected"<%} %>><%:color.Name %></option>
  <%} %>  
  </select>

(.aspx), :

<%=Html.EditorFor(x => x.ColorId, "ColorSelect", new { Colors = Model.ColorTable })%>

, -, , .

+1

, DropDownFor. , , SelectListItem , . .

+3

Source: https://habr.com/ru/post/1746385/


All Articles