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:
and in your controller:
and in your view: