2011-06-14 138 views

回答

4

有没有因为没有人打扰实施它。但是这样做很简单。例如,作为一个扩展方法(不幸的是扩展性能尚不支持.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"); 
} 
+0

好的,谢谢你。回答你的问题,为什么要为ViewData呢? – jaffa 2011-06-14 18:00:54

+2

@jaffa,我不知道,老实说,我不太在意它。无论如何,我从不需要和使用它们。对我来说,'ViewData/ViewBag'是邪恶的,它们的用法意味着设计不佳的ASP.NET MVC应用程序。 – 2011-06-14 18:37:35

相关问题