2015-03-16 9 views
10

ViewBag को साफ़ करने का कोई तरीका है?व्यूबैग साफ़ करें?

ViewBag कोई सेटर है, तो यह सिर्फ बाहर nulled नहीं किया जा सकता:

ViewBag = null; 

मैं भी इस पर पुनरावृति और उसके गतिशील गुण का सफाया करने के लिए use reflection नहीं कर पा रहे के रूप में आप नहीं कर सकते dynamic का उदाहरण बनाएं।

नोट: मुझे पता है कि ViewBag स्वयं कोड कोड की गंध है क्योंकि यह दृढ़ता से टाइप नहीं किया गया है, और मूल रूप से वैश्विक चर का विशाल संग्रह है। और हम इससे दूर जा रहे हैं, लेकिन इस दौरान भी इसके साथ निपटने की जरूरत है।

उत्तर

12

तुम बस

ViewData.Clear(); 

ViewBag वह आंतरिक रूप से उपयोग करता है के रूप में कह सकते हैं।

यहां उदाहरण उदाहरण है - https://dotnetfiddle.net/GmxctI। आप टिप्पणी हटाएं टिप्पणी की लाइन है, तो प्रदर्शित पाठ साफ कर दिया जाएगा

यहाँ MVC में ViewBag के लिए current implementation है:

public dynamic ViewBag 
{ 
    get 
    { 
     if (_dynamicViewDataDictionary == null) 
     { 
      _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData); 
     } 
     return _dynamicViewDataDictionary; 
    } 
} 

और वह DynamicViewDataDictionary

// Implementing this function improves the debugging experience as it provides the debugger with the list of all 
// the properties currently defined on the object 
public override IEnumerable<string> GetDynamicMemberNames() 
{ 
    return ViewData.Keys; 
} 

public override bool TryGetMember(GetMemberBinder binder, out object result) 
{ 
    result = ViewData[binder.Name]; 
    // since ViewDataDictionary always returns a result even if the key does not exist, always return true 
    return true; 
} 

public override bool TrySetMember(SetMemberBinder binder, object value) 
{ 
    ViewData[binder.Name] = value; 
    // you can always set a key in the dictionary so return true 
    return true; 
} 

का हिस्सा तो तुम इसे देख सकते हैं के रूप में ViewData ऑब्जेक्ट

+0

पर निर्भर करता है, धन्यवाद! जैसे ही एसओ मुझे देता है आपको आपको सही ढंग से अर्जित ✓ से सम्मानित किया जाएगा। –

+0

मुझे खुशी है कि इससे मदद मिली :) –

संबंधित मुद्दे