绑定枚举与下拉列表并设置所选值获取动作在MVC C# [英] Bind Enum with dropdown and set selected value on get action in MVC C#
本文介绍了绑定枚举与下拉列表并设置所选值获取动作在MVC C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个枚举
调用 CityType
public enum CityType
{
[Description("Select City")]
Select = 0,
[Description("A")]
NewDelhi = 1,
[Description("B")]
Mumbai = 2,
[Description("C")]
Bangalore = 3,
[Description("D")]
Buxar = 4,
[Description("E")]
Jabalpur = 5
}
从枚举生成列表
IList<SelectListItem> list = Enum.GetValues(typeof(CityType)).Cast<CityType>().Select(x => new SelectListItem(){
Text = EnumHelper.GetDescription(x),
Value = ((int)x).ToString()
}).ToList();
int city=0;
if (userModel.HomeCity != null) city= (int)userModel.HomeCity;
ViewData["HomeCity"] = new SelectList(list, "Value", "Text", city);
绑定.cshtml
@Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" })
EnumHelper GetDescription类获取枚举描述
EnumHelper GetDescription Class to get Description of Enum
推荐答案
这是我用于枚举的代码下拉菜单。
然后只需使用@ Html.DropDown / For();并将此SelectList作为参数。
This is the code I use for enums in dropdowns. Then just use @Html.DropDown/For(); and put this SelectList in as param.
public static SelectList ToSelectList(this Type enumType, string selectedValue)
{
var items = new List<SelectListItem>();
var selectedValueId = 0;
foreach (var item in Enum.GetValues(enumType))
{
FieldInfo fi = enumType.GetField(item.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
var title = "";
if (attributes != null && attributes.Length > 0)
{
title = attributes[0].Description;
}
else
{
title = item.ToString();
}
var listItem = new SelectListItem
{
Value = ((int)item).ToString(),
Text = title,
Selected = selectedValue == ((int)item).ToString(),
};
items.Add(listItem);
}
return new SelectList(items, "Value", "Text", selectedValueId);
}
还可以像这样扩展DropDownFor:
Also you can extend DropDownFor like this:
public static MvcHtmlString EnumDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Type enumType, object htmlAttributes = null)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
SelectList selectList = enumType.ToSelectList(metadata.Model.ToString());
return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}
使用方法如下所示:
Usage then looks like this:
@Html.EnumDropdownListFor(model => model.Property, typeof(SpecificEnum))
这篇关于绑定枚举与下拉列表并设置所选值获取动作在MVC C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文