为什么 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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)