[英]how to enumerate MVC 5 viewbag
Seems like viewbag is an instance of System.Web.Mvc.DynamicViewDataDictionary. 好像viewbag是System.Web.Mvc.DynamicViewDataDictionary的实例。 Which is internal and so I cant cast ViewBag to it. 这是内部的,因此我无法将ViewBag投射到它。 And that type doesn't expose an IDictionary interface (cf ExpandoObject) 而且该类型不会公开IDictionary接口(请参阅ExpandoObject)
So how can I do this 那我该怎么做
foreach(var kv in <ViewBag magic>)
{
.....
}
I see that System.Web.Mvc.DynamicViewDataDictionary has a Keys method but that doesn't help since I cannot get a dynamic object value dynamically. 我看到System.Web.Mvc.DynamicViewDataDictionary具有Keys方法,但这没有帮助,因为我无法动态获取动态对象值。 ie I cant do 即我不能
var k = "Key1";
var v = ViewBag[k];
The ViewData
property -- a ViewDataDictionary
-- will contain the same data as ViewBag
( ViewBag
is basically a wrapper around ViewData
). ViewData
属性(一个ViewDataDictionary
)将包含与ViewBag
相同的数据( ViewBag
基本上是ViewData
的包装器)。
A ViewDataDictionary
is a structure that can be iterated (it implements IDictionary<string, object>
and various IEnumerable
s): ViewDataDictionary
是可以迭代的结构(它实现IDictionary<string, object>
和各种IEnumerable
):
foreach (KeyValuePair<string, object> kvp in ViewData)
{
}
There are ways to cast ExpandoObject
s to IDictionary<string, object>
s but you're basically still in the same boat, since you will need to know what types you're working with to cast them from object
to something useful. 有多种方法可以将ExpandoObject
为IDictionary<string, object>
但是您基本上仍然处于同一条船上,因为您将需要知道要使用哪种类型将它们从object
强制转换为有用的类型。
The ViewBag acts as a wrapper on ViewData. ViewBag充当ViewData的包装器。 You can use reflection to enumerate the properties of a ViewBag . 您可以使用反射来枚举ViewBag的属性 。
PropertyInfo pInfo = ViewBag.GetType().GetProperty("ViewData",
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
var viewDataDictionary = pInfo.GetValue(ViewBag, null);
The resulting dictionary will have a set of Keys and Values that can be enumerated. 生成的字典将具有一组可以枚举的键和值。
Note: The ViewData property being reflected here is a Non Public member and you may want to decide between using a ViewBag and ViewData which directly permits enumeration. 注意:这里反映的ViewData属性是一个非公共成员,您可能需要在使用直接允许枚举的ViewBag和ViewData之间进行选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.