sev*_*dcg 6 asp.net-mvc html.dropdownlistfor kendo-ui
我正在努力更新应用程序以使用Kendo UI,并且遇到了使用DropDownList绑定到Enum的问题.我遇到的两个问题是:1)该值不包含Enum值,而是包含"Today"(应为0),以及2)显示值始终为"Last10Days"而不是"Last 10 Days"标签.我看了,找不到另一个地方,有人使用Kendo UI将描述显示为文本,并包含数值而不是文本.任何帮助表示赞赏.
<div class="span6">
@Html.LabelFor(m=> m.DateRanges)
@(Html.Kendo().DropDownListFor(m => m.DateRanges)
.BindTo(Enum.GetNames(typeof(SearchDateRanges)).ToList())
.HtmlAttributes(new { value = "Today" })
.DataTextField("Text")
.Events(e => e.Change("DateChange")))
</div>
<div class="span6">
@Html.LabelFor(m => m.Status)
@(Html.Kendo().DropDownListFor(m=> m.Status)
.BindTo(Enum.GetNames(typeof(SearchStatusCriteria)).ToList())
.HtmlAttributes(new {value = "All"}))
</div>
Run Code Online (Sandbox Code Playgroud)
public enum SearchDateRanges
{
[Description("Today")]
Today = 0,
[Description("Last 10 Days")]
Last10Days = 1,
/// <summary>
/// The last 30 days.
/// </summary>
[Description("Last 30 Days")]
Last30Days = 2,
[Description("Last 60 Days")]
Last60Days = 3,
[Description("Last 90 Days")]
Last90Days = 4,
[Description("Custom Date Range")]
CustomRange = 5
}
Run Code Online (Sandbox Code Playgroud)
}
AFAIK,自动不支持此功能.
您可以编写一个小辅助方法,它采用Enum类型并将其转换为List<SelectListItem>如下所示:
public static List<SelectListItem> EnumToSelectList( Type enumType )
{
return Enum
.GetValues( enumType )
.Cast<int>()
.Select( i => new SelectListItem
{
Value = i.ToString(),
Text = Enum.GetName( enumType, i ),
}
)
.ToList()
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将DropDownList绑定到选择列表:
.BindTo( EnumToSelectList( typeof( SearchDateRanges ) ) )
Run Code Online (Sandbox Code Playgroud)
如果您希望文本来自Description属性,则必须修改它以获取属性值 - 可能通过Reflection.
您似乎要求枚举的变量名称而不是描述属性:
.BindTo(Enum.GetNames(typeof(SearchDateRanges)).ToList())
Run Code Online (Sandbox Code Playgroud)
要获得描述属性,您必须做一些工作.这是我发现的一些代码:
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
Run Code Online (Sandbox Code Playgroud)
您还将文本字段绑定到枚举中不存在的"文本".
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
11481 次 |
| 最近记录: |