Domanda

We have a custom cache system in our MVC project where we save and load our model in controllers. We utilize the Viewbag object also, but we're having trouble finding a way to save the state of this object. It's also not marked as [Serializable] so a byte-array is no-go.

Can you save the state of the Viewbag object in some way to a manageable database object? Can you override or extend the behaviour of the Viewbag in some way?

I feel like scrapping Viewbag entirely.

È stato utile?

Soluzione

The ViewBag is a DynamicViewDataDictionary, which inherits DynamicObject. Getting the keys is straightforward using "GetDynamicMemberNames", but getting the values is slightly more verbose. The following converts the ViewBag to a dictionary (shamelessly plagiarized borrowed from Aaronaught's answer here):

var values = new Dictionary<string, object>();
IEnumerable<string> keys = ViewBag.GetDynamicMemberNames();
foreach (string key in keys)
{
    var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(
        CSharpBinderFlags.None, key, 
        ViewBag.GetType(),
        new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
    var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
    var val = callsite.Target(callsite, ViewBag);
    values.Add(key, val);
}

I feel like scrapping Viewbag entirely.

This sounds like a good idea -- far better to use strongly-typed view models, where possible.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top