2013-02-06 51 views
3

我有一个场景,我想从复选框列表中选择3个项目。这工作正常,但如果复选框的列表变长,该页面看起来很笨重。所以我想把它改成3个下拉列表。所以页面要小很多,但是没有一个下拉列表会兑现选定的值。将数组绑定到多个DropDownListFor

所以,我想这样的代码

@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 0 ? Model.CheckedLarcenyTypes[0] : null as Int32?), String.Empty, new { id = "Larceny1" }) 
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 1 ? Model.CheckedLarcenyTypes[1] : null as Int32?), String.Empty, new { id = "Larceny2" }) 
@Html.DropDownListFor(model => model.CheckedLarcenyTypes, new SelectList(Model.LarcenyTypes, "Key", "Value", Model.CheckedLarcenyTypes.Length > 2 ? Model.CheckedLarcenyTypes[2] : null as Int32?), String.Empty, new { id = "Larceny3" }) 

现在的下拉列表中正确创建和正确的价值得到约束,并在文章中,我看到的视图模型的价值越来越被送回。

我只是不能得到selectvalue显示在下拉列表中。在重新加载页面时,下拉菜单仍然是空白的。

我在这里做错了什么?这甚至有可能吗?

+0

嗨弗兰,如果列表很长,为什么不考虑一个替代解决方案,比如实现一个jQuery选择列表插件就像在http://loopj.com/jquery-tokeninput/中找到的一样,看看它是否会满足你的情况?与复选框列表不同,这将显示一个下拉列表,您可以从中选取条目。您选择的每个条目将在文本区域内列出 –

回答

2

您的问题与here有关。

如果您使用的是相同的模型回发期间接受来自编辑视图 输入读选择

,你可能会觉得默认的模型绑定将 重新填充专辑集合了所有的专辑信息和 设置选定的相册。不幸的是 - 网络不能以这种方式工作 和专辑收藏将是空的。

所以,你必须有这样的视图模型:

public class LarcenyViewModel 
{ 
    public int CheckedLarcenyType1 { get; set; } 
    public int CheckedLarcenyType2 { get; set; } 
    public int CheckedLarcenyType3 { get; set; }    
    public IEnumerable<SelectListItem> LarcenyTypes { get; set; } 
} 

填充视图模型是这样的:

LarcenyViewModel larcenyViewModel = new LarcenyViewModel(); 

// Use a database, enum or whatever to get the LarcenyTypes... :) 
larcenyViewModel.LarcenyTypes = new SelectList(
       database.FindAllLarcenyTypes(), "LarcenyId", "Name"); 

查看代码:

@Html.DropDownListFor(model => model.CheckedLarcenyType1, Model.LarcenyTypes, String.Empty, new { id = "Larceny1" }) 
@Html.DropDownListFor(model => model.CheckedLarcenyType2, Model.LarcenyTypes, String.Empty, new { id = "Larceny2" }) 
@Html.DropDownListFor(model => model.CheckedLarcenyType3, Model.LarcenyTypes, String.Empty, new { id = "Larceny3" }) 
+0

我已阅读您提到的帖子,实际上不是我看到的问题。我不希望模型联编程序绑定整个对象。我只是希望dropdownlist能像其他任何html对象一样工作。如果输入对象有一个名称,我的理解是它将绑定来自所有同名对象的值,它将这些项的值绑定到它的任何类型的数组中。我似乎已经留下了一个关键部分,这是我的视图模型。 CheckedLarcenyTypes被定义为Int32 []。这应该允许模型联编程序绑定这些值。 – Fran

+0

我明白你对此的失望,但是使用“ASP.NET MVC”的东西并不适用于这种方式。我建议你阅读这篇文章,了解如何建模绑定到列表和数组类型:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx –

+0

我创建了一个示例该应用程序显示了如何在操作方法中绑定到数组参数。你可以看看这里:https://github.com/leniel/AspNetMvcArrayDataBinding –

相关问题