我的视图中有一个静态下拉列表
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
我想将此下拉列表与我的模型绑定,以便当我提交下拉列表的选定值时,我从控制器中的模型中获取该值。
另外,我想根据模型中的数据选择下拉选项。
答案 0 :(得分:6)
我刚刚制作了静态下拉列表的列表项目&amp;将它传递到下拉列表,我将其与我的viewmodel绑定。
@{
var listItems = new List<ListItem> {new ListItem {Text = "Single", Value = "Single"}, new ListItem {Text = "Married", Value = "Married"}, new ListItem {Text = "Divorse", Value = "Divorse"}};
}
@Html.DropDownListFor(model => model.EmployeeDetail.MaritalStatus, new SelectList(listItems),"-- Select Status --")
它对我来说非常有效,因为它显示了来自模型和模型的价值。当我提交数据时,还会在模型中存储下拉列表的值。
答案 1 :(得分:3)
不是在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
}
OR
[HttpPost]
public ActionResult SomeSaveAction()
{
var model = someService.BuildYourViewModel()
this.TryUpdateModel(model);
// do something with the model...
someService.SaveYourViewModel(model);
}
我希望这会有所帮助......
答案 2 :(得分:0)
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Volvo", Value = "volvo"});
items.Add(new SelectListItem { Text = "Saab", Value = "saab" });
items.Add(new SelectListItem { Text = "Mercedes", Value = "mercedes" });
items.Add(new SelectListItem { Text = "Audi", Value = "audi" });
在视图
上Html.DropDownListFor(Model.items)