问题 清除ViewBag?


有没有办法清除 ViewBag

ViewBag 没有二传手,所以它不能简单地被淘汰:

ViewBag = null;

我也似乎无法 用反射 迭代它并消除其动态属性,因为你无法创建一个实例 dynamic

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


3419
2018-03-16 20:17


起源



答案:


你可以打电话

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 目的


13
2018-03-16 20:21



那就做到了,谢谢!一旦SO让我,你就会被授予你合法获得的奖励。 - Jerad Rose
我很高兴它有帮助:) - Sergey Litvinov


答案:


你可以打电话

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 目的


13
2018-03-16 20:21



那就做到了,谢谢!一旦SO让我,你就会被授予你合法获得的奖励。 - Jerad Rose
我很高兴它有帮助:) - Sergey Litvinov