如果有用于ViewData的ViewBag,为什么没有用于TempData的TempBag?

问题描述

| 为什么没有TempData的动态字典对象和ViewData的动态字典对象?     

解决方法

        不是因为没有人愿意执行它。但这很容易做到。例如,作为一种扩展方法(不幸的是,.NET中尚不支持扩展属性,因此您无法完全获得所需的语法):
public class DynamicTempDataDictionary : DynamicObject
{
    public DynamicTempDataDictionary(TempDataDictionary tempData)
    {
        _tempData = tempData;
    }

    private readonly TempDataDictionary _tempData;

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _tempData.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder,out object result)
    {
        result = _tempData[binder.Name];
        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder,object value)
    {
        _tempData[binder.Name] = value;
        return true;
    }
}

public static class ControllerExtensions
{
    public static dynamic TempBag(this ControllerBase controller)
    {
        return new DynamicTempDataDictionary(controller.TempData);
    }
}
接着:
public ActionResult Index()
{
    this.TempBag().Hello = \"abc\";
    return RedirectToAction(\"Foo\");
}
问题是:为什么您会需要它?它比以下哪个更好/更安全?
public ActionResult Index()
{
    TempData[\"Hello\"] = \"abc\";
    return RedirectToAction(\"Foo\");
}