Вот как я это сделал:
Я создал свой собственный DropDownListFor:
public static MvcHtmlString TheDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> listOfValues, string placeHolder)
{
var model = htmlHelper.ViewData.Model;
var metaData = ModelMetadata .FromLambdaExpression(expression, htmlHelper.ViewData);
var tb = new TagBuilder("select");
if (listOfValues != null)
{
tb.MergeAttribute("id", metaData.PropertyName);
tb.MergeAttribute("name", metaData.PropertyName);
if (!string.IsNullOrEmpty(placeHolder))
{
var option = new TagBuilder("option");
option.MergeAttribute("value", placeHolder);
tb.InnerHtml += option.ToString();
}
foreach (var item in listOfValues)
{
var option = new TagBuilder("option");
option.MergeAttribute("value", item.Value);
var textNdata = item.Text.Split('|');
option.InnerHtml = textNdata[0];
if (textNdata.Length == 2)
option.MergeAttribute("data-name", textNdata[1]);
if(item.Selected)
option.MergeAttribute("selected", "selected");
tb.InnerHtml += option.ToString();
}
}
return MvcHtmlString.Create(tb.ToString());
}
Тогда мой SelectListItem List
создается так:
public List<SelectListItem> EmployerList
{
get
{
return Employers.Select(x => new SelectListItem
{
Text = x.EAN + "|" + x.Name,
Value = x.Id.ToString(),
Selected = (SelectedEmployer != null && SelectedEmployer.Id == x.Id)
}).ToList();
}
}