C# 将列表框选择绑定到模型属性
我一直在努力将Html helper中的MultiSelectList绑定到特定的模型 型号C# 将列表框选择绑定到模型属性,c#,asp.net,asp.net-mvc,listbox,C#,Asp.net,Asp.net Mvc,Listbox,我一直在努力将Html helper中的MultiSelectList绑定到特定的模型 型号 在我的模型中,我有如下内容: public class DefaultSelection { public SelectionItem Selection1 {get;set;} public SelectionItem Selection2 {get;set;} public SelectionItem Selection3 {get;set;} public IEn
在我的模型中,我有如下内容:
public class DefaultSelection
{
public SelectionItem Selection1 {get;set;}
public SelectionItem Selection2 {get;set;}
public SelectionItem Selection3 {get;set;}
public IEnumerable<SelectionItem> Items{get;set;}
public DefaultSelection()
{
Selection1 = new SelectionItem(true, "Item1");
Selection2 = new SelectionItem(false, "Item2");
Selection3 = new SelectionItem(true, "Item3");
Items = new List<SelectionItem>(new SelectionItem[]
{Selection1,Selection2,Selection3});
}
}
public class SelectionItem
{
public bool Selected {get;set;}
public string Name {get;set;}
public SelectionItem(bool selected, string name)
{
Selected = selected;
Name = name;
}
}
不幸的是,既没有正确显示所选项目(没有选择任何内容),也没有选择对模型产生任何影响
有办法解决这个问题吗?我可以去掉这个Items属性吗,因为它只是对所需属性的引用?我认为这比您想象的要容易得多。让我们试一试 创建良好的视图模型:
公共类默认选择
{
公共IEnumerable项{get;set;}
//设置一个属性以保存选定的项目ID。
公共IEnumerable SelectedItems{get;set;}
公共默认选择()
{
//预选功能
项目=新列表
{
新建SelectListItem{Text=“Item1”,Selected=true},
新建SelectListItem{Text=“Item2”,Selected=false},
新建SelectListItem{Text=“Item3”,Selected=true}
};
}
}
在视图中呈现列表框:
@LabelFor(x=>x.Items)
@Html.ListBoxFor(x=>x.SelectedItems,Model.Items,new{@class=“selectpicker”})
请注意,我在这里使用的是内置的System.Web.Mvc.SelectListItem
类,而不是自定义的SelectionItem
——您可以安全地摆脱它
现在,您将在发布后在模型中获得所选项目id(在本例中为名称,因为您在创建项目时未指定value属性)
希望这有帮助 您的
@Html.ListBoxFor
应该是这样的
@Html.ListBoxFor(model => model.SelectedNames, new MultiSelectList(Model.Items,"Name", "Name",Model.Items.Where(x=>x.Selected).Select(x=>x.Name)), new { @class = "selectpicker" })
您必须指定Model.Items的值字段和文本字段,它们是“Name”,“Name”
和Model.Items。其中(x=>x.Selected)。选择(x=>x.Name)
将选择选择为true的所有值,但您的模型将返回字符串列表中的值,因此您应该定义一个字段
public List<string> SelectedNames { get; set; }
public List SelectedNames{get;set;}
您将在此处获得所选项目的值请参阅此“为我工作的罚款”的可能副本!非常感谢。
<div class="form-group">
@Html.LabelFor(x => x.Items)
@Html.ListBoxFor(x => x.SelectedItems, Model.Items, new { @class = "selectpicker" })
</div>
@Html.ListBoxFor(model => model.SelectedNames, new MultiSelectList(Model.Items,"Name", "Name",Model.Items.Where(x=>x.Selected).Select(x=>x.Name)), new { @class = "selectpicker" })
public List<string> SelectedNames { get; set; }