2

我们的 MVC 项目中有一个自定义缓存系统,我们在控制器中保存和加载模型。我们也使用了 Viewbag 对象,但是我们很难找到一种方法来保存这个对象的状态。它也没有被标记为 [Serializable] 所以字节数组是不行的。

您能否以某种方式将 Viewbag 对象的状态保存到可管理的数据库对象中?你能以某种方式覆盖或扩展 Viewbag 的行为吗?

我想完全废弃 Viewbag。

4

1 回答 1

4

ViewBag 是一个DynamicViewDataDictionary,它继承了DynamicObject. 使用“GetDynamicMemberNames”获取密钥很简单,但获取值稍微冗长一些。以下将 ViewBag 转换为字典(无耻抄袭Aaronaught 的答案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);
}

我想完全废弃 Viewbag。

这听起来是个好主意——在可能的情况下使用强类型视图模型要好得多。

于 2013-08-26T19:06:48.007 回答