我有一组下拉列表,通过循环列表动态添加:
for (int i = 0; i < Model.WindowGlassItems.Count; i++)
{
@Html.DropDownListFor(gu => gu.WindowGlassItems[i], Model.WindowGlassTypes, "-- Select --", new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
WindowGlassItems的类型为List<int?>
即使此列表设置为值
问题是什么?
EDIT,目前正在使用这个hack,虽然有效,但我不满意,如果可能,仍然会更喜欢适当的MVC解决方案
@Html.Hidden("HiddenWindowGlassItems", string.Join(",", Model.WindowGlassItems.Select(s => s.ToString()).ToArray()))
JS:
var glassCSV = $("#HiddenWindowGlassItems").val();
if (glassCSV != null) {
var array = glassCSV.split(',');
for (var i = 0; i < array.length; i++) {
$("#Glass" + i + " option[value='" + array[i] + "']").attr("selected", "selected");
}
}
仅供参考
选择的名称如下: WindowGlassItems [0]
<select name="WindowGlassItems[0]" id="Glass0" data-val-number="The field Nullable`1 must be a number." data-val="true" class="form-control glass-multi-select"><option value="">-- Select --</option>
<option value="637">Tint</option>
etc...
<select name="WindowGlassItems[1]" id="Glass1" data-val-number="The field Nullable`1 must be a number." data-val="true" class="form-control glass-multi-select"><option value="">-- Select --</option>
<option value="637">Tint</option>
etc...
依旧......
答案 0 :(得分:2)
DropDownListFor
无法在任何地方获取所选值。表达式go => go.WindowGlassItems[i]
仅指定模型映射(此处生成的Html元素的名称和ID)
for (int i = 0; i < Model.WindowGlassItems.Count; i++)
{
@Html.DropDownListFor(
gu => gu.WindowGlassItems[i], // This is the selected value.
new SelectList(Model.WindowGlassTypes, Model.WindowGlassItems[i])
"-- Select --",
new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
使用new SelectList()
答案 1 :(得分:2)
最终这起作用了:
(这个答案有帮助:MVC looping in razor, generated dropdownlist not value selected)
for (int i = 0; i < Model.WindowGlassUnitsCount; i++)
{
@Html.DropDownListFor(gu => gu.WindowGlassItems[i],
new SelectList(Model.WindowGlassTypes,"Value","Text", Model.WindowGlassItems[i]),
//Model.WindowGlassTypes,
"-- Select --", new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
答案 2 :(得分:0)
如果要预先选择项目,则Model.WindowGlassTypes集合必须是IList类型。 System.Web.Mvc.SelectListItem有一个布尔属性Selected,您需要将true设置为要选择的元素。