Html 多选列表如何与 ASP.NET MVC 中的模型绑定一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1255472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does a multiple select list work with model binding in ASP.NET MVC?
提问by
If you have a select list set to multiple in ASP.NET MVC, how does the modelbinding work?
如果您在 ASP.NET MVC 中将选择列表设置为多个,那么模型绑定如何工作?
What does it return for your selected items, an array?
它为您选择的项目返回什么,一个数组?
<SELECT NAME="toppings" MULTIPLE SIZE=5>
<option value="mushrooms">mushrooms</option>
<option value="greenpeppers">green peppers</option>
<option value="onions">onions</option>
<option value="tomatoes">tomatoes</option>
<option value="olives">olives</option>
</SELECT>
回答by Sam Wessel
Yes, by default a multiselectlist will post through an array of the selected values.
是的,默认情况下,多选列表将通过选定值的数组发布。
This articlehas further information, including how to use strongly-typed views with a multiselectlist.
本文提供了更多信息,包括如何在多选列表中使用强类型视图。
From the linked "article":
从链接的“文章”:
- Your model or view model class needs a collection property for the IDs for the selected option items, e.g.
List<int> ToppingIds
. - In the controller action method to which the form containing your multi-select-list POSTs, you can access the selected option items thru the collection property you added to the model or view model class.
- 您的模型或视图模型类需要所选选项项的 ID 的集合属性,例如
List<int> ToppingIds
. - 在包含多选列表 POST 的表单的控制器操作方法中,您可以通过添加到模型或视图模型类的集合属性访问选定的选项项。
回答by Hbas
Yes, it returns an array.
是的,它返回一个数组。
View model:
查看型号:
public class MyViewModel
{
public int[] SelectedIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
控制器:
public ActionResult Index()
{
var model = new MyViewModel
{
// fetch the items from some data source
Items = Enumerable.Select(x => new SelectListItem
{
Value = x.Id,
Text = "item " + x.Id
})
};
return View(model);
}
View:
看法:
@model MyViewModel
@Html.ListBoxFor(x => x.SelectedIds, Model.Items)
回答by Sreenath Plakkat
In VegTableViewmodel:
在 VegTableView 模型中:
public IEnumerable<MultiSelectList> Vegetables { get; set; }
In the Controller: Get vegetables list, and then pass it to the VegTableViewModel's Vegetables property.
在Controller中:获取蔬菜列表,然后将其传递给VegTableViewModel的Vegetables属性。
viewmodel.Vegetables = vegetables .Select(d => new MultiSelectList(d.VegName));
In the View:
在视图中:
@Html.ListBoxFor(m => m.L, new MultiSelectList(Model.Vegetables.Select(d => d.Items))