C#是否可以为多个选项建模?

时间:2016-03-28 08:41:17

标签: c# asp.net asp.net-mvc model-binding multiple-instances

我有一个下拉列表,您可以选择多个选项。 enter image description here

此下拉列表的代码为: enter image description here

如何绑定多个设备'在C#中,以便在加载此下拉列表时 模型绑定会自动选择传递给视图的所有选项吗?

3 个答案:

答案 0 :(得分:1)

模型中的Devices属性应该是Ids列表(其中是一个简单的类型,如int或字符串)而不是Device模型列表(因为你在Helper中使用new SelectList(Model.Devices, "ID", "Description")它是我看到的那个Model.Devices是一个复杂对象的集合)

所以你的模型应该是这样的:

public List<Device> AvailableDevices { get;set; }

public List<string> Devices { get;set; }

和助手应该是

@Html.ListBoxFor(m=>m.Devices,new SelectList(Model.AvailableDevices , "ID", "Description"))

@Html.DropDownListFor(m=>m.Devices,new SelectList(Model.AvailableDevices , "ID", "Description", new {multiple="multiple"})

后期操作应该接收List<string>作为参数或完整模型:

[HttpPost]
public ActionResult Submit(List<string> devices)

[HttpPost]
public ActionResult Submit(YourModel model) 
//where YourModel model is the same type that you are using to render your view

答案 1 :(得分:1)

在这种情况下,我会在viewmodel

中执行以下操作
public string Devices { get; set; }
List<int> innerList;
public List<int> List
{
    get
    {
        if (this.innerList == null)
        {
            if (string.IsNullOrEmpty(this.Devices))
            {
                this.innerList = this.Devices.Split(',').Select(x => int.Parse(x)).ToList();
            }
            else
            {
                this.innerList = new List<int>();
            }
        }

        return this.innerList;
    }
}

Devices是带有下拉列表的绑定属性,它返回由,分隔的所有项目。 当您尝试访问List时,它会将这些项目分开并将其作为List<int>返回。

我正在将其解析为int,因为通常我会将int&#39; s视为ID&#39>

但我期待着更好的选择。

<强> PS

我在使用Select2

时这样做

答案 2 :(得分:1)

对于您的情况,您应该使用另一个帮助者 - @Html.ListBoxFor它应该生成具有select属性的multiple元素。

//note that i use MaintanceDevices property
@Html.ListBoxFor(x => x.MaintanceDevices, new SelectList(Model.Devises, "ID", "Description"), new { @class = "multiselect form-control"})

此外,请勿在帮助程序中设置id属性。最好在ViewModel中创建另一个属性:

public List<int> MaintanceDevices { get; set; }

在Controller中填充它,MVC会自动为表单POST中的select元素绑定生成正确的标记。

相关问题