在ASP.net MVC中从Enum下拉列表中选择的项目

Ale*_*use 13 c# asp.net-mvc

对不起,如果这是一个副本,我的搜索没有任何结果.

我使用以下方法生成枚举类型的下拉列表(从这里解除:http://addinit.com/?q = node/54):

public static string DropDownList(this HtmlHelper helper, string name, Type type, object selected)
{
    if (!type.IsEnum)
        throw new ArgumentException("Type is not an enum.");

    if(selected != null && selected.GetType() != type)
        throw new ArgumentException("Selected object is not " + type.ToString());

    var enums = new List<SelectListItem>();
    foreach (int value in Enum.GetValues(type))
    {
        var item = new SelectListItem();
        item.Value = value.ToString();
        item.Text = Enum.GetName(type, value);

        if(selected != null)
            item.Selected = (int)selected == value;

        enums.Add(item);
     }

    return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums, "--Select--");
}
Run Code Online (Sandbox Code Playgroud)

除了一件事,它工作正常.如果我给下拉列表提供与我的模型上的属性相同的名称,则未正确设置所选值.这意味着:

<%= Html.DropDownList("fam", typeof(EnumFamily), Model.Family)%>
Run Code Online (Sandbox Code Playgroud)

但这不是:

<%= Html.DropDownList("family", typeof(EnumFamily), Model.Family)%>
Run Code Online (Sandbox Code Playgroud)

因为我试图将整个对象直接传递给我发布的控制器方法,所以我真的希望在模型上为该属性命名下拉列表.当使用"正确"名称时,下拉列表会正确发布,我似乎无法设置所选值.

我不认为这很重要,但我在单声道2.6上运行MVC 1

编辑:我刚刚在Windows上测试了这个,我看到了同样的行为

egl*_*ius 14

不要使用enum /的int值而不是:

item.Value = value.ToString();

使用:

item.Value = Enum.GetName(type, value);

imo正在发生的事情是它自动设置下拉列表的选定值以匹配模型 - 使用枚举名称而不是其int值.请记住,视图引擎不仅会在已发布的表单中查找已选择的值(在已经发布的情况下),而且还会在模型+ viewdata中传递给视图.只有当它没有找到它时,它才会使用您指定的选定值.