I have an entity, lets say Person:
class Person
{
id Id { get; set; }
string Name { get; set; }
int RoleId { get; set; }
}
This RoleId property corresponds to a role selected from a list of available Roles. I pass this list of roles to the view using the ViewData object:
List<SelectListItem> roles = new List<SelectListItem>()
{
new SelectListItem(){ Text = "User", Value = "0"},
new SelectListItem(){ Text = "Admin", Value = "1"}
};
ViewData["roles"] = roles;
(Note I use strings as values here as it doesn’t let me use integers?)
My View (it’s an “add” view, to create a new Person) inherits from the Person entity. I am unsure how to setup the dropdown list in the view so that the value of the selected item in the list gets set as the RoleId property value in the Person object that is sent back to the Controller (for the HttpPost method).
This being said it is not a code that I would recommend. Everytime I see someone using ViewData my temperature raises.
I would use view models:
and then in your controller:
and in your strongly typed view: