Razor DropDownListFor:向 SelectList 选项标签添加额外的属性

Sha*_*anc 5 asp.net-mvc html-select razor

我正在尝试创建一个选择列表。我使用视图模型中的集合创建了它,该集合允许我使用以下代码设置每个选项的值和文本:

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

Model.Networks 包含另一个名为 CountryId 的属性。我想为每个选项标签添加一个属性,如下所示:

<option value="[NetworkId]" data-countryId="[CountryId]">Canada</option>
Run Code Online (Sandbox Code Playgroud)

我应该怎么做?

sam*_*mbo 6

您可以创建一个 Form Helper 类来创建一个自定义下拉列表,并创建一个自定义的“selectListItem”类,该类具有一个额外的 IDictionary 类型的属性“itemsHtmlAttributes”——见下文。您可能需要使用 '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);
    }
}
Run Code Online (Sandbox Code Playgroud)

看法:

@{
    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))
}
Run Code Online (Sandbox Code Playgroud)