如何在.NET的MVC中执行Enum绑定到视图的模型? [英] How do I perform an Enum binding to a view's model in .NET's MVC?
本文介绍了如何在.NET的MVC中执行Enum绑定到视图的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将枚举绑定到MVC中的一个下拉列表中,使模型在发布后有效?
不确定它需要一个转换器或其他东西,我提供的代码,你推荐的解决方案是什么?
(以下代码导致ModelError)
How can I bind an enum into a drop down in MVC to make the model be valid after a post? Not sure does it need a converter or something else, I provide the code, what is your recommended solution? (the below code causes ModelError)
枚举:
public enum TimePlan
{ Routine = 0,
Single = 1 }
模型:
public TimePlan TheTimePlan { get; set; }
public SelectListItem[] TimeList { get; set; }
控制器:
[HttpPost]
public virtual ActionResult Education(EducationViewModel EducationModelInfo)
{
if (ModelState.IsValid)
{ ...
} }
查看绑定
@Html.DropDownListFor(m => m.CourseTimePlan, Model.TimeList, "Please select the time plan")
推荐答案
您没有显示如何填充此TimeList集合。尝试这样,它应该工作:
You haven't shown how you populated this TimeList collection. Try like this and it should work:
public TimePlan TheTimePlan { get; set; }
public IEnumerable<SelectListItem> TimeList
{
get
{
var enumType = typeof(TimePlan);
var values = Enum.GetValues(enumType).Cast<TimePlan>();
var converter = TypeDescriptor.GetConverter(enumType);
return
from value in values
select new SelectListItem
{
Text = converter.ConvertToString(value),
Value = value.ToString(),
};
}
}
或者让它更通用你可以写一个可重用的帮助器:
or to make it a little more generic you could write a reusable helper:
public static IHtmlString DropDownListForEnum<TModel, TEnum>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var enumType = GetNonNullableModelType(metadata);
var values = Enum.GetValues(enumType).Cast<TEnum>();
var converter = TypeDescriptor.GetConverter(enumType);
var items =
from value in values
select new SelectListItem
{
Text = converter.ConvertToString(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
return htmlHelper.DropDownListFor(expression, items);
}
然后您的模型只能包含枚举值:
and then your model could only contain the Enum value:
public TimePlan TheTimePlan { get; set; }
,在你看来使用助手:
@Html.DropDownListForEnum(x => x.TheTimePlan)
这篇关于如何在.NET的MVC中执行Enum绑定到视图的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文