I have the following, which posts "IT" and "HR" as values in model. I want IT and HR as Label, and 0 and 1 as values to controller.
@Html.DropDownList("DepartmentId", new SelectList(new[] { "IT", "HR" }))
And when i get the view, how can i have pre-selected value in the dropdown with the matching value in Department ID in model. So if an item has Id as HR, the dropdown should already have HR as selected, and then a person can change it to IT, and that option can be saved.
Any Help ?? Please note i don't want to change my model.
ANSWER Big Thanks to Terry Nederveld for giving this answer :
@Html.DropDownList("DepartmentId", new SelectList(new[] { new KeyValuePair<string, int>("IT", 1), new KeyValuePair<string, int>("HR", 2) }, "Value", "Key", (Model.ServiceItem.DepartmentId.Equals(1) ? 1 : 2)))
Assuming you're using MVC3/4, the easiest way is to add a 'Departments' property to your model. Then you can do this in your view:
With your model looking like this:
This takes care of selecting the correct item.
See the response from eudaimos (about 50% of way down replies) here for a solution
David Masters approach is the one that I use normally. But since you don't want to change the Model. Here is one approach that will work: