Razor DropDownListFor: adding an additional attribute to the SelectList options tag

I am trying to create a picklist. I created it just fine, using the collection from my view model, which allows me to set each parameter value and text with the following code:

@Html.DropDownListFor(model => model.Networks, new SelectList(Model.Networks, "NetworkID", "Name"), new { @class="form-control" })

Model.Networks contains another property called CountryId. I would like to add an attribute for each parameter tag so that it looks like this:

<option value="[NetworkId]" data-countryId="[CountryId]">Canada</option>

In what order should I do this?

+3
source share
1 answer

Form Helper selectListItem, 'itemsHtmlAttributes' IDictionary - . . , "id" "name", . , TagBuilder 'select' 'option':

public class SelectListItemCustom : SelectListItem
{
    public IDictionary<string, object> itemsHtmlAttributes { get; set; }
}

public static class FormHelper
{
    public static MvcHtmlString DropDownListForCustom(this HtmlHelper htmlHelper, string id, List<SelectListItemCustom> selectListItems)
    {
        var selectListHtml = "";

        foreach (var item in selectListItems)
        {
            var attributes = new List<string>();
            foreach (KeyValuePair<string, string> dictItem in item.itemsHtmlAttributes)
            {
                attributes.Add(string.Format("{0}='{1}'", dictItem.Key, dictItem.Value));
            }
            // do this or some better way of tag building
            selectListHtml += string.Format(
                "<option value='{0}' {1} {2}>{3}</option>", item.Value,item.Selected ? "selected" : string.Empty,string.Join(" ", attributes.ToArray()),item.Text);
        }
        // do this or some better way of tag building
        var html = string.Format("<select id='{0}' name='{0}'>{1}</select>", id, selectListHtml);

        return new MvcHtmlString(html);
    }
}

VIEW:

@{
    var item = new SelectListItemCustom { Selected = true, Value = "123", Text = "Australia", itemsHtmlAttributes = new Dictionary<string, object> { { "countrycode", "au" } } };
    var items = new List<SelectListItemCustom> { item };

    Html.Raw(Html.DropDownListForCustom("insertIdHere", items))
}
+3

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


All Articles