2
我有一個DropDownList,它包含渲染視圖時正確的項目和值,但所選值未保存在指定實體字段Garage中。目前,正在保存並返回的值在創建或編輯後期方法中均爲0(無)。我敢肯定,這是簡單的,但我無法弄清楚......先謝謝了!無法將枚舉值從DropDownList保存到實體字段中 - EF Code First MVC3
模型類:
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; }
}
控制創建和編輯方法均是這樣的:
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)
這改正了我的問題與創建,現在正確的值被保存在表字段Garage中。當我嘗試編輯同一記錄時,DropDownList不會從創建條目時使用相同的選定值進行填充。該值被設置回零。我將這一行添加到創建和編輯方法@ Html.DropDownList(「GarageEnumValue」,(SelectList)ViewBag.GarageId,String.Empty) – Shawn
我發現我最後一個問題的解決方案是不使用第一個字符串參數GrageEnumValue,而是直接進入屬性Garage:@ Html.DropDownList(「Garage」,(SelectList)ViewBag.GarageId,String.Empty)感謝您的幫助!〜 – Shawn
請參閱我的DDL教程http://www.asp.net/mvc/ tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc and http://blogs.msdn.com/b/rickandy/archive/2012/ 01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT