C# – There is no ViewData item of type ‘IEnumerable‘ that has the key ‘Profession’

asp.net-mvc-2cdrop-down-menu

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 }),
                "value", "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?

Best Answer

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) %>