2011-03-09 25 views
7

我必須將選擇列表添加到註冊頁面。我想將選定的項目保存在數據庫中。我有類似的東西:沒有類型爲'IEnumerable <SelectListItem>'的ViewData項目具有關鍵字'Profession'

鑑於頁:

<%: Html.DropDownListFor(m => m.Profession, (IEnumerable<SelectListItem>)ViewData["ProfessionList"])%>     
<%: Html.ValidationMessageFor(m => m.Profession)%> 

在模型類:

並在控制器:

ViewData["ProfessionList"] = 
       new SelectList(new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5"} 
       .Select(x => new { value = x, text = x }), 
       "value", "text"); 

而且我得到錯誤:不是類型爲「IEnumerable」的具有關鍵字「專業」的ViewData項目。

我能做些什麼來使它工作?

+0

將其轉換爲「SelectList」,爲什麼要將它轉換爲IEnumerable ?? DropDownListFor方法接受selectList。 –

+0

我把它投在「SelectList」中,但是我得到了同樣的錯誤。我認爲它期望IEnumerable 這就是爲什麼我使用它。 – Marta

回答

8

你可以只定義的SelectList在您查看這樣的:

<%: Html.DropDownListFor(m => m.Profession, new SelectList(new string[] {"Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}, "Prof1"))%> 
       <%: Html.ValidationMessageFor(m => m.Profession)%> 
12

我建議使用視圖模型而不是ViewData。所以:

public class MyViewModel 
{ 
    [Required] 
    [DisplayName("Profession")] 
    public string Profession { get; set; } 

    public IEnumerable<SelectListItem> ProfessionList { get; set; } 
} 

,並在你的控制器:

public ActionResult Index() 
{ 
    var professions = new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5" } 
     .Select(x => new SelectListItem { Value = x, Text = x }); 
    var model = new MyViewModel 
    { 
     ProfessionList = new SelectList(professions, "Value", "Text") 
    }; 
    return View(model); 
} 

,並在您的視圖:

<%: Html.DropDownListFor(m => m.Profession, Model.ProfessionList) %> 
<%: Html.ValidationMessageFor(m => m.Profession) %> 
相關問題