不要在 HTML 中构建下拉列表,而是在您的服务/控制器中构建它并将其添加到您的模型中:
视图模型:
public class YourViewModel
{
public string SelectedCarManufacturer { get; set; }
public Dictionary<string, string> CarManufaturers { get; set; }
// your other model properties
}
控制器获取操作方法
[HttpGet]
public ActionResult SomeAction()
{
var model = new YourViewModel
{
SelectedCarManufacturer = null, // you could get this value from your repository if you need an initial value
CarManufaturers = new Dictionary<string, string>
{
{ "volvo", "Volvo" },
{ "saab", "Saab" },
{ "audi", "Audi" },
/// etc.
}
};
return this.View(model);
}
在您看来,将硬编码下拉列表替换为:
@Html.DropDownListFor(m => m.SelectedCarManufacturer , new SelectList(Model.CarManufaturers , "Key", "Value"), "Select a manufacturer...")
控制器后操作方法
[HttpPost]
public ActionResult SomeSaveAction(YourViewModel model)
{
// do something with the model...
// model.SelectedCarManufacturer
}
或者
[HttpPost]
public ActionResult SomeSaveAction()
{
var model = someService.BuildYourViewModel()
this.TryUpdateModel(model);
// do something with the model...
someService.SaveYourViewModel(model);
}
我希望这有帮助...