" that has the key "Profession", I need to add a selection list to the registrati...">

There is no ViewData element of type "IEnumerable <SelectListItem>" that has the key "Profession",

I need to add a selection list to the registration page. And I want to keep the selected item in a date. I have something like this:

On the watch page:

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

In the model class:

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

And in the controller:

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

And I get the error: there is no ViewData element of type "IEnumerable" that has the key "Profession".

What can I do to make it work?

+7
source share
2 answers

You can simply define a SelectList in your view as follows:

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

I would recommend using 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 opinion:

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

All Articles