shenn
shenn

Reputation: 887

Issue with dropdownlistfor in MVC

I am trying to submit a form using MVC4 and cannot seem to figure out why an error is coming after submittion. I have pasted all of the related code below as well as the error I have been seeing.

Error:

The ViewData item that has the key 'Group' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

Controller:

[HttpGet]
public ActionResult CreateRole()
{
var RM = new myModel();
RM.Groups = RM.InitializeGroupList();
return View(RM);
}

[HttpPost]
public ActionResult Myfunction(myModel model)

if (ModelState.IsValid)
{
//Execute Update
}

Model:

[Required]
[Display(Name = "Group")]
public string Group { get; set; }


public IEnumerable<SelectListItem> Groups;  

public IEnumerable<SelectListItem> InitializeGroupList()
    {
        List<SelectListItem> topOfList = new List<SelectListItem>
        {
            new SelectListItem { Value = string.Empty, Text = "Category" },
            new SelectListItem { Value = "Administrator", Text = "Administrator" },
            new SelectListItem { Value = "Partner", Text = "Partner" },
            new SelectListItem { Value = "Internal", Text = "Internal" }
        };
        //IEnumerable<SelectListItem> list = db.GetRoleList(topOfList);
        IEnumerable<SelectListItem> list = topOfList;
        return new SelectList(list, "Value", "Text");
    }

[Required]
[Display(Name = "Group")]
public string Group { get; set; }


public IEnumerable<SelectListItem> Groups;

View:

    @Html.DropDownListFor(model => model.Group, Model.Groups)

Upvotes: 0

Views: 150

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

That's because in your HttpPost controller action you forgot to populate the Groups property on your view model in the case when you rendered the same view:

RM.Groups = RM.InitializeGroupList();

Don't forget that the DropDownList sends only the selected value when you submit the form. The other values is up to you to retrieve the same way you did in your GET action if you intend to redisplay the same view.

Upvotes: 1

Related Questions