【问题标题】:Clear the ViewBag?清除 ViewBag?
【发布时间】:2015-03-16 20:17:40
【问题描述】:
有什么办法可以清除ViewBag?
ViewBag 没有设置器,因此不能简单地将其清空:
ViewBag = null;
我似乎也无法 use reflection 对其进行迭代并清除其动态属性,因为您无法创建 dynamic 的实例。
注意:我知道 ViewBag 本身有点代码味道,因为它不是强类型的,基本上是一个巨大的全局变量集合。我们正在远离它,但同时仍需要处理它。
【问题讨论】:
标签:
c#
asp.net-mvc
viewbag
【解决方案1】:
你可以打电话
ViewData.Clear();
因为 ViewBag 在内部使用它。
这是工作示例 - https://dotnetfiddle.net/GmxctI。
如果您取消注释注释行,则显示的文本将被清除
这是 MVC 中 ViewBag 的 current implementation:
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 对象