问题
I have the following dropdown list but the selected value doesn't seem to working. It defaults to first item in list.
private List<string> GetTransmissions()
{
List<string> Transmission = new List<string>();
Transmission.Add("Automatic");
Transmission.Add("Manual");
return Transmission;
}
Car car = _repository.GetCarDetails(id);
ViewBag.Transmission = new SelectList(GetTransmissions(), car.Transmission);
In my view I have:
@Html.DropDownList("Transmission", (IEnumerable<SelectListItem>)ViewBag.Transmission, "Please Select", new { @class = "form-control" })
回答1:
You need to differentiate the property that holds the list and the property that holds the selected value.
I recommend using a viewmodel for the view like this:
public class CarViewModel
{
public SelectList Transmissions
{
get
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Value = "Manual"},
new SelectListItem { Value = "Automatic"}
});
}
}
public string Transmission { get; set; }
}
and use this DropDownListFor version
@Html.DropDownListFor(model => model.Transmission,
@Model.Transmissions, "Please Select", new { @class = "form-control" })
回答2:
If you are restricted to using ViewBag
rather than a View Model and an @Html.DropDownList
Html Helper then I would do the following:
ViewBag.Transmissions = new SelectList(GetTransmissions()
.Select(t => new {value = t, text = t}),
"value", "text");
ViewBag.Transmission = car.Transmission;
The above creates the SelectList
, then projects so that your dropdown renders text and values. This is saved in the ViewBag.Transmissions
, which is the available options.
Then set your selected transmission with ViewBag.Transmission
.
Your razor code would also need to be changed to use ViewBag.Transmissions
too:
@Html.DropDownList("Transmission",
(IEnumerable<SelectListItem>)ViewBag.Transmissions,
"Please Select", new { @class = "form-control" })
Working Fiddle
回答3:
Managed to fix by changing
ViewBag.Transmission = new SelectList(GetTransmissions(), car.Transmission);
To
ViewBag.Transmissions = new SelectList(GetTransmissions(), car.Transmission);
The Car model already contains an attribute called Transmission so need need for another ViewBag to hold this attribute.
In the my razor code use the following instead
@Html.DropDownList("Transmission", (IEnumerable<SelectListItem>)ViewBag.Transmissions, "Please Select", new { @class = "form-control" })
来源:https://stackoverflow.com/questions/31295193/asp-mvc-dropdown-list-selected-value-not-selected