Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
Marta Avatar asked Mar 09 '11 11:03

Marta


2 Answers

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) %>
like image 127
Darin Dimitrov Avatar answered Sep 28 '22 00:09

Darin Dimitrov


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)%>
like image 23
Marta Avatar answered Sep 28 '22 01:09

Marta