微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 清除ViewBag?

有没有办法清除ViewBag?

ViewBag没有setter,所以它不能简单地被清空:

ViewBag = null;

我也似乎无法迭代它,并消除其动态属性,因为您无法创建动态实例.

注意:我自己知道ViewBag是一个代码气味,因为它不是强类型,而且基本上是一个巨大的全局变量集合.而我们正在离开它,但在此期间仍然需要处理它.

解决方法

你可以打电话
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对象

原文地址:https://www.jb51.cc/csharp/94428.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐