2013-01-14 152 views
1

像在DropDownListFor enums in EF5我想從代碼優先生成一個下拉列表EF枚舉。該解決方案提供了工作,但不會設置選定的值。我如何做到這一點?我曾嘗試下面的代碼,但它不工作(其中的SelectList最後一個參數重新代表所選值:DropDownListFor EF5選定項目中的枚舉

@Html.DropDownListFor(model => model.TypeID, new SelectList(Enum.GetValues(typeof(Models.OrganisationType)),model.TypeID)) 

我已經回答了我的問題上面的代碼正確地設置在下拉列表中選擇的值。出於某種原因,MVC不喜歡我的枚舉和屬性名時,我用這個詞「標題」我的財產,「圖書」我的枚舉如下:

@Html.DropDownListFor(model => model.Title, new SelectList(Enum.GetValues(typeof(BL.Titles)),Model.Title),"") 

而且我使用兩個創建一個視圖和編輯,因此必須添加代碼以阻止MVC嘗試在創建對象之前設置所選值:

@if(Model == null) { 
      @Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle))),"") 
     } 
     else 
     { 
      @Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle)),Model.PersonsTitle),"") 
     } 

有沒有人知道更優雅的方式?

回答

0

此:

@Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle))))) 

應該夠了。

我不喜歡你的條件:

@if(型號== NULL)你應該把你的模型中定義

和財產 「PersonsTitle」 應與您的默認設置值。