0

如何将枚举绑定到 MVC 中的下拉列表中以使模型在发布后有效?不确定它是否需要转换器或其他东西,我提供了代码,您推荐的解决方案是什么? (以下代码导致 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") 
4

1 回答 1

9

您尚未展示如何填充此 TimeList 集合。像这样尝试,它应该可以工作:

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(),
            };
    }
}

或者让它更通用一点,你可以编写一个可重用的助手:

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);
}

然后您的模型只能包含 Enum 值:

public TimePlan TheTimePlan { get; set; }

并在您看来使用助手:

@Html.DropDownListForEnum(x => x.TheTimePlan)
于 2013-08-15T08:17:57.427 回答