หากมี ViewBag สำหรับ ViewData เหตุใดจึงไม่มี TempBag สำหรับ TempData

เหตุใดจึงไม่มีวัตถุพจนานุกรมแบบไดนามิกสำหรับ TempData เช่นเดียวกับ ViewData


person jaffa    schedule 14.06.2011    source แหล่งที่มา


คำตอบ (1)


ไม่ใช่เพราะไม่มีใครใส่ใจที่จะใช้มัน แต่นั่นคงเป็นเรื่องง่ายที่จะทำ ตัวอย่างเช่นเป็นวิธีการขยาย (น่าเสียดายที่คุณสมบัติส่วนขยายยังไม่รองรับใน .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");
}
person Darin Dimitrov    schedule 14.06.2011
comment
โอเค ขอบคุณสำหรับสิ่งนั้น เพื่อตอบคำถามของคุณ ทำไมต้องมี ViewData ล่ะ? - person jaffa; 14.06.2011
comment
@ จาฟฟา ฉันไม่มีความคิดและค่อนข้างตรงไปตรงมาฉันไม่สนใจเรื่องนี้มากนัก ฉันไม่เคยจำเป็นและใช้มันเลย สำหรับฉัน ViewData/ViewBag นั้นชั่วร้ายและการใช้งานบ่งบอกถึงแอปพลิเคชัน ASP.NET MVC ที่ออกแบบมาไม่ดี - person Darin Dimitrov; 14.06.2011