我正在尝试创建一个选择列表。我使用viewmodel中的一个集合创建它很好,它允许我使用以下代码设置每个选项的值和文本:
@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>
我应该采用哪种方式进行此操作?
答案 0 :(得分:4)
您可以创建一个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);
}
}
查看:
@{
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))
}