【发布时间】:2012-06-14 23:18:39
【问题描述】:
我正在使用 ASP.NET MVC 3,但使用DropDownListFor HTML Helper 时遇到了“问题”。
我在控制器中执行此操作:
ViewBag.ShippingTypes = this.SelectListDataRepository.GetShippingTypes();
还有GetShippingTypes 方法:
public SelectList GetShippingTypes()
{
List<ShippingTypeDto> shippingTypes = this._orderService.GetShippingTypes();
return new SelectList(shippingTypes, "Id", "Name");
}
我把它放在ViewBag 而不是模型中(我为每个视图都有强类型模型)的原因是我有一个使用 EditorTemplate 呈现的项目集合,它还需要访问 ShippingTypes选择列表。
否则我需要遍历整个集合,然后分配一个 ShippingTypes 属性。
到目前为止一切顺利。
在我看来,我这样做:
@Html.DropDownListFor(m => m.RequiredShippingTypeId, ViewBag.ShippingTypes as SelectList)
(RequiredShippingTypeId 是 Int32 类型)
发生的情况是,RequiredShippingTypeId 的值在下拉列表中没有被选中。
He suggests that MVC will lookup the selected value from ViewData, when the select list is from ViewData.我不确定是否是这种情况,因为博客文章已经过时了,而且他在谈论 MVC 1 beta。
解决此问题的解决方法是:
@Html.DropDownListFor(m => m.RequiredShippingTypeId, new SelectList(ViewBag.ShippingTypes as IEnumerable<SelectListItem>, "Value", "Text", Model.RequiredShippingTypeId.ToString()))
我尽量不在最后RequiredShippingTypeId 上ToString,这给了我与以前相同的行为:未选择任何项目。
我认为这是一个数据类型问题。最终,HTML 助手将字符串(在选择列表中)与Int32(来自RequiredShippingTypeId)进行比较。
但是为什么将 SelectList 放在 ViewBag 中时它不起作用 - 当它在将它添加到模型时完美地工作,并在视图中执行此操作:
@Html.DropDownListFor(m => m.Product.RequiredShippingTypeId, Model.ShippingTypes)
【问题讨论】:
-
感谢您的解决方法!如此不明显,魔术只适用于“简单”的 lambda 表达式,并且系统不会给出任何警告。
标签: asp.net-mvc-3