【发布时间】:2011-06-15 00:21:57
【问题描述】:
为什么 TempData 没有像 ViewData 那样的动态字典对象?
【问题讨论】:
标签: asp.net-mvc-3
为什么 TempData 没有像 ViewData 那样的动态字典对象?
【问题讨论】:
标签: asp.net-mvc-3
没有因为没有人费心去实现它。但这很容易做到。例如作为一种扩展方法(不幸的是,.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/ViewBag 是邪恶的,它们的使用意味着 ASP.NET MVC 应用程序设计不佳。