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?
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)%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With