为什么没有TempBag为TempData的

为什么没有TempBag为TempData的

本文介绍了如果有ViewBag为ViewData的,为什么没有TempBag为TempData的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么那里的TempData没有动态字典对象,因为是ViewData的?

Why is there no dynamic dictionary object for TempData as there is for ViewData?

推荐答案

有没有因为没有人会费心去实现它。但是这将是很轻松的事情。例如作为一个扩展方法(不幸的是扩展性能尚不支持.NET,所以你不能完全得到你可能希望的语法):

There isn't because no-one ever bothered to implement it. But that would be trivially easy to do. For example as an extension method (unfortunately extension properties are not yet supported in .NET so you cannot quite get the syntax you might have hoped for):

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");
}

问题是:为什么你需要的又是怎样更好/更安全比:

The question is: why would you need that and how is it better/safer than:

public ActionResult Index()
{
    TempData["Hello"] = "abc";
    return RedirectToAction("Foo");
}

这篇关于如果有ViewBag为ViewData的,为什么没有TempBag为TempData的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:50