Create Labels and Values for HTML DropDownList in

2019-06-06 10:10发布

问题:

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)))

回答1:

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")) 


回答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:

@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.



回答3:

See the response from eudaimos (about 50% of way down replies) here for a solution