如何在下拉框中绑定枚举类型
1个回答
展开全部
给你一个我写的
/// <summary>
/// 转换一个枚举到SelectList,指定一个int值来选择默认选择项
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="enumObj"></param>
/// <param name="selected"></param>
/// <returns></returns>
public static SelectList ToSelectList<TEnum>(this TEnum enumObj, int selected)
{
try
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new SelectListItem { Value = (Convert.ToInt32(e).ToString()), Text = e.ToString() };
return new SelectList(values, "Value", "Text", selected);
}
catch
{
return new SelectList(new List<string> { "转换枚举类型到列表时出现错误" }, selected);
}
}
用的时候 @Html.DropDownListFor(model => model.ExpertIsWork, Consts.YesNo.是.ToSelectList(0))
/// <summary>
/// 转换一个枚举到SelectList,指定一个int值来选择默认选择项
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="enumObj"></param>
/// <param name="selected"></param>
/// <returns></returns>
public static SelectList ToSelectList<TEnum>(this TEnum enumObj, int selected)
{
try
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new SelectListItem { Value = (Convert.ToInt32(e).ToString()), Text = e.ToString() };
return new SelectList(values, "Value", "Text", selected);
}
catch
{
return new SelectList(new List<string> { "转换枚举类型到列表时出现错误" }, selected);
}
}
用的时候 @Html.DropDownListFor(model => model.ExpertIsWork, Consts.YesNo.是.ToSelectList(0))
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询