剃刀DropDownListFor:添加额外属性的SelectList选项标记 [英] Razor DropDownListFor: Adding Extra Attribute To SelectList Option Tag
问题描述
我试图创建一个选择列表。我使用从我的视图模型集合,让我来设置每个选项的值和文本有以下code创建它就好了:
I'm trying to create a select list. I've created it just fine using a collection from my viewmodel that allows me to set each option's value and text with the following code:
@Html.DropDownListFor(model => model.Networks, new SelectList(Model.Networks, "NetworkID", "Name"), new { @class="form-control" })
Model.Networks包含一个名为CountryId另一个属性。我想一个属性添加到每个选项标签,这样它看起来像:
Model.Networks contains another property called CountryId. I'd like to add an attribute to each option tag so it looks like:
<option value="[NetworkId]" data-countryId="[CountryId]">Canada</option>
我应该走哪条路这样做?
Which way should I go about doing this?
推荐答案
您可以创建一个表单辅助类来创建一个自定义的下拉列表中,并创建一个自定义的selectListItem'类有一个额外的属性itemsHtmlAttributes型IDictionary的 - 见下文。您可能需要玩的'身份证'或'名称'属性来获取默认的模型绑定工作。下面是一个有点乱,我会建议使用TagBuilder打造的选择和选项标签:
You can create a Form Helper class to create a custom drop down list, and create a custom 'selectListItem' class that has an extra property 'itemsHtmlAttributes' of type IDictionary - see below. You may need to play around with the 'id' or 'name' attributes to get the default model binding working. Below is a bit messy, I would suggest using TagBuilder to build the 'select' and 'option' tags:
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))
}
这篇关于剃刀DropDownListFor:添加额外属性的SelectList选项标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!