【问题标题】:Unable to save Enum values into entity field from DropDownList - EF Code First MVC3无法将枚举值从 DropDownList 保存到实体字段中 - EF Code First MVC3
【发布时间】:2012-06-10 04:22:56
【问题描述】:

我有一个 DropDownList,它在呈现视图时包含正确的项目和值,但选定的值没有保存在指定的实体字段 Garage 中。目前在创建或编辑帖子方法中保存和返回的值都是 0(无)。我确定这很简单,但我无法弄清楚......提前致谢!

模型类:

public enum GarageType { None = 0, One = 1, Two = 2, Three = 3, Four = 4 }

public int Garage { get; set; }

[NotMapped]
public GarageType GarageEnumValue
{
    get { return (GarageType)Garage; }
    set{ Garage = (int)value; }
}

Control Create 和 Edit 方法都如下所示:

var statuses = from Property.GarageType s in Enum.GetValues(typeof(Property.GarageType))
                       select new { ID = (int)s, Name = s.ToString() };
ViewBag.GarageId = new SelectList(statuses, "ID", "Name", statuses.FirstOrDefault().ID);

最后的观点:

@Html.DropDownList("GarageId", String.Empty)

【问题讨论】:

    标签: asp.net-mvc ef-code-first


    【解决方案1】:

    使用DropDownList方法的以下重载

    @Html.DropDownList("GarageEnumValue", (SelectList)ViewBag.GarageId, String.Empty)
    

    如果您有强类型模型,请使用

    @Html.DropDownListFor(m => m.GarageEnumValue, (SelectList)ViewBag.GarageId, String.Empty)
    

    这两种情况下的第一个参数应该是您要绑定列表的属性

    【讨论】:

    • 这纠正了我的创建问题,现在正确的值被保存在表字段 Garage 中。当我尝试编辑同一条记录时,DropDownList 不会填充与我创建条目时相同的选定值。该值被设置回零。我将此行添加到创建和编辑方法 @Html.DropDownList("GarageEnumValue", (SelectList)ViewBag.GarageId, String.Empty)
    • 我发现我最后一个问题的解决方案是不使用第一个字符串参数 GrageEnumValue 而是直接转到属性 Garage:@Html.DropDownList("Garage", (SelectList)ViewBag.GarageId, String.Empty) 感谢您的帮助!~
    • 哇,这是关于如何在 MVC 中编写 DropDownList 的精彩内容,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多