首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >清除ViewBag?

清除ViewBag?
EN

Stack Overflow用户
提问于 2015-03-16 20:17:40
回答 1查看 14.2K关注 0票数 12

有没有办法清除ViewBag

ViewBag没有setter,所以不能简单地取消:

代码语言:javascript
复制
ViewBag = null;

我也不能让use reflection迭代它并消除它的动态属性,因为您不能创建一个dynamic实例。

注意:我知道ViewBag本身有点代码味道,因为它不是强类型的,基本上是一个庞大的全局变量集合。我们正在远离它,但在此期间仍然需要处理它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-16 20:21:09

你可以直接打电话

代码语言:javascript
复制
ViewData.Clear();

因为ViewBag在内部使用它。

下面是工作示例- https://dotnetfiddle.net/GmxctI。如果取消注释行,则显示的文本将被清除。

以下是MVC中的current implementation for ViewBag:

代码语言:javascript
复制
public dynamic ViewBag
{
    get
    {
        if (_dynamicViewDataDictionary == null)
        {
            _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);
        }
        return _dynamicViewDataDictionary;
    }
}

以及DynamicViewDataDictionary的一部分

代码语言:javascript
复制
// 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对象

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29086179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档