Ответ 1
Вы можете просто позвонить
ViewData.Clear();
Поскольку ViewBag использует его внутренне.
Вот рабочий пример - https://dotnetfiddle.net/GmxctI. Если вы раскомментируете прокомментированную строку, то отображаемый текст будет очищен
Вот текущая реализация для ViewBag в MVC:
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