2011-06-14 135 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

相關問題