我正在使用 ASP.NET MVC 3,并且刚刚使用 DropDownListFor
遇到了“陷阱” HTML 助手。
我在我的 Controller 中这样做:
ViewBag.ShippingTypes = this.SelectListDataRepository.GetShippingTypes();
和
GetShippingTypes
方法:public SelectList GetShippingTypes()
{
List<ShippingTypeDto> shippingTypes = this._orderService.GetShippingTypes();
return new SelectList(shippingTypes, "Id", "Name");
}
我把它放在
ViewBag
的原因而不是在模型中(我为每个 View 都设置了强类型模型),是我有一个使用 EditorTemplate 呈现的项目集合,它也需要访问 ShippingTypes 选择列表。否则我需要遍历整个集合,然后分配一个 ShippingTypes 属性。
到现在为止还挺好。
在我看来,我这样做:
@Html.DropDownListFor(m => m.RequiredShippingTypeId, ViewBag.ShippingTypes as SelectList)
(
RequiredShippingTypeId
是 Int32
类型)发生的情况是,
RequiredShippingTypeId
的值未在下拉列表中选择。我遇到了这个:http://web.archive.org/web/20090628135923/http://blog.benhartonline.com/post/2008/11/24/ASPNET-MVC-SelectList-selectedValue-Gotcha.aspx
他建议 MVC 将从
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()))
我尽量不
ToString
在 RequiredShippingTypeId
最后,这给了我与以前相同的行为:未选择任何项目。我认为这是一个数据类型问题。最终,HTML 助手将字符串(在选择列表中)与
Int32
进行比较。 (来自 RequiredShippingTypeId
)。但是为什么将 SelectList 放入
ViewBag
时不起作用? -- 在将其添加到模型中并在 View 中执行此操作时,它可以完美运行:@Html.DropDownListFor(m => m.Product.RequiredShippingTypeId, Model.ShippingTypes)
最佳答案
这不起作用的原因是因为 DropDownListFor
的限制助手:它能够使用作为第一个参数传递的 lambda 表达式来推断选定的值 仅当 这个 lambda 表达式是一个简单的属性访问表达式。例如,由于编辑器模板,这不适用于数组索引器访问表达式,这是您的情况。
您基本上拥有(不包括编辑器模板):
@Html.DropDownListFor(
m => m.ShippingTypes[i].RequiredShippingTypeId,
ViewBag.ShippingTypes as IEnumerable<SelectListItem>
)
不支持以下内容:
m => m.ShippingTypes[i].RequiredShippingTypeId
.它仅适用于简单的属性访问表达式,但不适用于索引集合访问。您找到的解决方法是解决此问题的正确方法,即在构建
SelectList
时显式传递所选值。 .
关于asp.net-mvc-3 - ASP.NET MVC DropDownListFor not select value from model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11042660/