【问题标题】:Razor DropDownListFor: Adding Extra Attribute To SelectList Option TagRazor DropDownListFor:向 SelectList 选项标签添加额外属性
【发布时间】:2013-10-03 23:56:17
【问题描述】:

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

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

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

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

我应该怎么做?

【问题讨论】:

    标签: asp.net-mvc razor html-select


    【解决方案1】:

    您可以创建一个表单助手类来创建一个自定义下拉列表,并创建一个自定义“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);
        }
    }
    

    查看:

    @{
        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))
    }
    

    【讨论】:

    • 我无法让这段代码工作 - 我在“ForEach”方法上收到一个错误,说 IDictionary 定义中不存在该方法。
    • foreach (KeyValuePair
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多