【问题标题】:If there is ViewBag for ViewData, why is there no TempBag for TempData?如果 ViewData 有 ViewBag,为什么 TempData 没有 TempBag?
【发布时间】:2011-06-15 00:21:57
【问题描述】:

为什么 TempData 没有像 ViewData 那样的动态字典对象?

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    没有因为没有人费心去实现它。但这很容易做到。例如作为一种扩展方法(不幸的是,.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");
    }
    

    【讨论】:

    • 好的,谢谢。在回答您的问题时,为什么要使用 ViewData 呢?
    • @jaffa,我不知道,老实说,我不太关心它。无论如何,我从来不需要和使用它们。对我来说,ViewData/ViewBag 是邪恶的,它们的使用意味着 ASP.NET MVC 应用程序设计不佳。
    猜你喜欢
    • 2011-12-21
    • 2011-06-09
    • 2012-09-22
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多