2011-03-09 23 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) %> 
相关问题