没有类型为'IEnumerable <SelectListItem>'的ViewData项具有键'Profession'

Mar*_*rta 7 c# asp.net-mvc-2 drop-down-menu

我必须将选择列表添加到注册页面.我想在datebase中保存所选项目.我有类似的东西:

在视图页面中:

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

在模型类中:

[Required]
[DisplayName("Profession")]
public string Profession { get; set; } 
Run Code Online (Sandbox Code Playgroud)

在控制器中:

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

我收到错误:没有类型为'IEnumerable'的ViewData项具有关键'Profession'.

我能做些什么才能让它发挥作用?

Dar*_*rov 12

我建议使用视图模型而不是ViewData.所以:

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

    public IEnumerable<SelectListItem> ProfessionList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并在您的控制器中:

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);
}
Run Code Online (Sandbox Code Playgroud)

在你看来:

<%: Html.DropDownListFor(m => m.Profession, Model.ProfessionList) %>
<%: Html.ValidationMessageFor(m => m.Profession) %>
Run Code Online (Sandbox Code Playgroud)


Mar*_*rta 8

您可以在视图中定义SelectList,如下所示:

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