Reputation: 3070
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)))
Upvotes: 1
Views: 6316
Reputation: 8295
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:
@Html.DropDownListFor(m => m.Department.DepartmentId, Model.Departments)
With your model looking like this:
public class ViewModel
{
public List<SelectListItem> Departments
{
get;
private set;
}
public Department Department { get; set; }
public ViewModel()
{
Departments = new List<SelectListItem>();
//Assume you'll be getting the list from db here?
Departments .Add(new SelectListItem { Text = "HR", Value = "IdValueHere" });
Departments .Add(new SelectListItem { Text = "IT", Value = "IdValueHere" });
}
}
This takes care of selecting the correct item.
Upvotes: 3
Reputation: 722
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:
@Html.DropDownList("Departments", new SelectList(new [] { new KeyValuePair<string, int>( "IT", 0 ), new KeyValuePair<string, int>( "HR", 1 )},"Value", "Key"))
Upvotes: 2