加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 清除ViewBag?

发布时间:2020-12-15 06:50:42 所属栏目:百科 来源:网络整理
导读:有没有办法清除ViewBag? ViewBag没有setter,所以它不能简单地被清空: ViewBag = null; 我也似乎无法迭代它,并消除其动态属性,因为您无法创建动态实例. 注意:我自己知道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对象

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读