我对MVC3很新,并开发了DropDownListFor,我需要同时获取值和文本以显示结果。有关这个问题的任何想法?谢谢!
在我的控制器中:
ViewBag.vehicleSizes = totalGreenCalculator.GreenCalculator.getVehicleFuelEfficiency();
在我的模型中:
//Datatype: fuelEfficiency = double, vehicleSizes = string
public IEnumerable<SelectListItem> getVehicleFuelEfficiency()
{
var size = new[] {new vehicleSize {fuelEfficiency = 0.0, vehicleSizes = "Choose your vehicle size"},
//and so on
};
return size.Select(a => new SelectListItem() { Text = a.vehicleSizes, Value = a.fuelEfficiency.ToString() });
}
查看:
@Html.DropDownListFor(model => model.GreenCalculator.vehicleList[i].fuelEfficiency, (IEnumerable<SelectListItem>)ViewBag.vehicleSizes)
答案 0 :(得分:0)
您可以在控制器上接收
答案 1 :(得分:0)
您的代码看起来很好。它将从给定值生成下拉列表。但它不会预先选择默认选项。那是因为在第一个参数中你使用了复杂的表达式。如果你想预先选择一些项目,你可以这样做:
@Html.DropDownListFor(
x => x.GreenCalculator.vehicleList[i].fuelEfficiency,
new SelectList(
(IEnumerable<SelectListItem>)ViewBag.vehicleSizes,
"Value",
"Text",
Model.GreenCalculator.vehicleList[i].fuelEfficiency
)
)