[英]Clear the ViewBag?
有没有办法清除ViewBag
?
ViewBag
没有setter,所以它不能简单地被淘汰:
ViewBag = null;
我似乎也无法使用反射来迭代它并消除其动态属性,因为您无法创建dynamic
实例。
注意:我知道ViewBag
本身就有点代码味道,因为它不是强类型的,并且基本上是全局变量的巨大集合。 我们正在远离它,但在此期间仍然需要处理它。
你可以打电话
ViewData.Clear();
由于ViewBag在内部使用它。
这是工作示例 - https://dotnetfiddle.net/GmxctI 。 如果取消注释注释行,则将清除显示的文本
以下是MVC中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
对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.