我知道这篇文章很旧,但我在寻找相同问题的答案时遇到了它。我最终编写了一个 FormattableSelectList 类,该类将格式字符串作为参数,然后格式化选择列表的输出。这是如何使用它的示例。
@Html.DropDownFor(
o => o.SomeProperty,
new FormattableSelectList(ViewBag.MyItems, "ID", "Time", "{0:f}"),
"Choose a Time"
)
我在http://www.jpolete.me/2011/11/16/a-formattable-selectlist-for-net-mvc/上写了一篇关于它的短文。这是它的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Web.UI;
using System.Globalization;
public class FormattableSelectList : SelectList
{
private string _FormatString;
public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString)
: base(items, dataValueField, dataTextField)
{
_FormatString = formatString;
}
public FormattableSelectList(IEnumerable items, string dataValueField, string dataTextField, string formatString, object selectedValue)
: base(items, dataValueField, dataTextField, selectedValue)
{
_FormatString = formatString;
}
public override IEnumerator<SelectListItem> GetEnumerator()
{
return ((!String.IsNullOrEmpty(DataValueField)) ?
GetListItemsWithValueField() :
GetListItemsWithoutValueField()).GetEnumerator();
}
private IList<SelectListItem> GetListItemsWithValueField()
{
HashSet<string> selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (SelectedValues != null)
{
selectedValues.UnionWith(from object value in SelectedValues select Convert.ToString(value, CultureInfo.CurrentCulture));
}
var listItems = from object item in Items
let value = Eval(item, DataValueField, null)
select new SelectListItem
{
Value = value,
Text = Eval(item, DataTextField, _FormatString),
Selected = selectedValues.Contains(value)
};
return listItems.ToList();
}
private IList<SelectListItem> GetListItemsWithoutValueField()
{
HashSet<object> selectedValues = new HashSet<object>();
if (SelectedValues != null)
{
selectedValues.UnionWith(SelectedValues.Cast<object>());
}
var listItems = from object item in Items
select new SelectListItem
{
Text = Eval(item, DataTextField, _FormatString),
Selected = selectedValues.Contains(item)
};
return listItems.ToList();
}
private static string Eval(object container, string expression, string formatString)
{
object value = container;
if (!String.IsNullOrEmpty(expression))
{
value = DataBinder.Eval(container, expression);
}
string stringValue;
if (formatString == null)
{
stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
}
else
{
stringValue = String.Format(formatString, value);
}
return stringValue;
}
}