开发者

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Profession'

I have to add select list to registration page. And I want to save selected item in datebase. I have something like that:

In view page:

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

In model class:

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

And in controller:

ViewData["ProfessionList"] =
                new SelectList(new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}
                .Select(x => new { value = x, text = x }),
                "val开发者_如何转开发ue", "text");

And I am getting error: There is no ViewData item of type 'IEnumerable' that has the key 'Profession'.

What can I do to make it work?


I would recommend the usage of view models instead of ViewData. So:

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

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

and in your controller:

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);
}

and in your view:

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


You can just define SelectList in you view like that:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜