I am having issues posting a viewmodel which contains a dictionary. Each time I receive the model at my controller action, all values are null (really only the dictionary values that I need) and I'm not sure how to resolve this or why it's happening. Below you can find my view (nonrelevant parts excluded), my controller, and the viewmodel I am using. The idea here is to pass a dictionary relating users to roles, allow an admin to edit the various user roles, then pass the information back to the controller to update the DB with the new role info. I have had luck serializing IEnumerables in the past (Lists, etc) this way but cant get it to work for a dictionary. All help is appreciated.
The View:
@model RecipeManager.ViewModels.AdminViewModel
@{
ViewBag.Title = "Index";
}
<h2>Admin</h2>
@using (Html.BeginForm("UpdateRoles", "Admin", FormMethod.Post))
{
<div>
@for (int i = 0; i < Model.UsersAndRoles.Count; i++)
{
<strong>@Model.UsersAndRoles.ElementAt(i).Key.UserName</strong>
@Html.DropDownListFor(m => m.UsersAndRoles.ElementAt(i).Value, Model.RoleTypes, Model.UsersAndRoles.ElementAt(i).Value, new { @class = "form-control" })
}
</div>
<input type="submit" value="Update Roles" />
}
An example of the html produced a username and the admin role dropdown:
<strong>test+cook@test.com</strong> <select class="form-control" id="Value" name="Value"><option value="">Cook</option>
<option value="1">Admin</option>
<option value="2">Cook</option>
<option value="3">Retail</option>
</select>
The Controller Action (in AdminController
):
[AuthorizeUser(Activity = "ViewAdmin")]
[HttpPost]
public ActionResult UpdateRoles(AdminViewModel vm)
{
return View("Index");
}
And the ViewModel (AdminViewModel
):
namespace RecipeManager.ViewModels
{
public class AdminViewModel
{
public SelectList RoleTypes { get; set; }
public String SelectedRole { get; set; }
public String InviteEmailAddress { get; set; }
public Dictionary<ApplicationUser, string> UsersAndRoles { get; set; }
}
}