有没有办法清除ViewBag?
ViewBag没有setter,所以不能简单地取消:
ViewBag = null;我也不能让use reflection迭代它并消除它的动态属性,因为您不能创建一个dynamic实例。
注意:我知道ViewBag本身有点代码味道,因为它不是强类型的,基本上是一个庞大的全局变量集合。我们正在远离它,但在此期间仍然需要处理它。
发布于 2015-03-16 20:21:09
你可以直接打电话
ViewData.Clear();因为ViewBag在内部使用它。
下面是工作示例- https://dotnetfiddle.net/GmxctI。如果取消注释行,则显示的文本将被清除。
以下是MVC中的current implementation for ViewBag:
public dynamic ViewBag
{
get
{
if (_dynamicViewDataDictionary == null)
{
_dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewDataDictionary;
}
}以及DynamicViewDataDictionary的一部分
// Implementing this function improves the debugging experience as it provides the debugger with the list of all
// the properties currently defined on the object
public override IEnumerable<string> GetDynamicMemberNames()
{
return ViewData.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = ViewData[binder.Name];
// since ViewDataDictionary always returns a result even if the key does not exist, always return true
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
ViewData[binder.Name] = value;
// you can always set a key in the dictionary so return true
return true;
}所以正如您所看到的,它依赖于ViewData对象
https://stackoverflow.com/questions/29086179
复制相似问题