为什么 Html.DropDownListFor 需要额外的转换?
在我的控制器中,我创建了一个 SelectListItems 列表,并将其存储在 ViewData 中。当我在视图中读取 ViewData 时,它会给出有关类型不正确的错误。如果我手动转换类型,它可以工作,但似乎这应该自动发生。有人可以解释一下吗?
控制器:
enum TitleEnum { Mr, Ms, Mrs, Dr };
var titles = new List<SelectListItem>();
foreach(var t in Enum.GetValues(typeof(TitleEnum)))
titles.Add(new SelectListItem()
{ Value = t.ToString(), Text = t.ToString() });
ViewData["TitleList"] = titles;
视图:
// Doesn't work
Html.DropDownListFor(x => x.Title, ViewData["TitleList"])
// This Works
Html.DropDownListFor(x => x.Title, (List<SelectListItem>) ViewData["TitleList"])
In my controller I create a list of SelectListItems and store this in the ViewData. When I read the ViewData in my View it gives me an error about incorrect types. If I manually cast the types it works but seems like this should happen automatically. Can someone explain?
Controller:
enum TitleEnum { Mr, Ms, Mrs, Dr };
var titles = new List<SelectListItem>();
foreach(var t in Enum.GetValues(typeof(TitleEnum)))
titles.Add(new SelectListItem()
{ Value = t.ToString(), Text = t.ToString() });
ViewData["TitleList"] = titles;
View:
// Doesn't work
Html.DropDownListFor(x => x.Title, ViewData["TitleList"])
// This Works
Html.DropDownListFor(x => x.Title, (List<SelectListItem>) ViewData["TitleList"])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为
ViewData
是一个Dictionary
。还有什么方法可以在带键的集合中存储多种类型的对象呢?任何从ViewData
检索而无需转换的内容都将被编译器视为基本Object
。Because
ViewData
is aDictionary<string, Object>
. How else could you store objects of multiple types in a keyed collection? Anything retrieved fromViewData
without casting will be treated by the compiler as a baseObject
.如果我没记错的话,ViewData 是一个对象数组/集合。这就是为什么需要额外的演员阵容。
If I remember correctly, ViewData is an array/collection of objects. This is why the extra cast is needed.
显然,编译器不会自动执行从 object 类型的对象到另一种类型的转换。我希望 ViewData 的结果在编译时是对象类型。示例如下:
Apparently the compiler will not perform a cast from an object of type object to another type automatically. I expect that results from ViewData are of type object at compile time. Example follows:
这是因为一种称为“静态类型”的功能。有些人喜欢它,有些人讨厌它。
It's because of a feature called "static typing". Some love it, others hate it.
如果您更改
为
并再次尝试:
如果这有效,我会同意 Femaref....不过是个好问题。
what if you change
to
and again try it with:
if this works, the I would agree with Femaref....good question though.