如何ViewBag在ASP.NET MVC的作品 [英] How ViewBag in ASP.NET MVC works

查看:168
本文介绍了如何ViewBag在ASP.NET MVC的作品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ASP.NET MVC的 ViewBag 工作? MSDN说,这仅仅是一个对象,这令我着迷,如何做魔术师的属性,如 ViewBag.Foo 和魔术字符串 ViewBag [你好] 实际工作?

How does the ASP.NET MVC's ViewBag work? MSDN says it is just an Object, which intrigues me, how does "Magic" properties such as ViewBag.Foo and magic strings ViewBag["Hello"] actually work?

另外,我怎样才能做一个,在我的ASP.NET应用程序的WebForms使用它?

Also, how can I make one and use it in my ASP.NET WebForms app?

例子将是非常美联社preciated!

Examples would be really appreciated!

推荐答案

ViewBag 的类型为动态但是,在内部的 System.Dynamic.ExpandoObject()

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

据声明如下:

动态ViewBag =新System.Dynamic.ExpandoObject();

这就是为什么你可以这样做:

which is why you can do :

ViewBag.Foo =酒吧;

一个示例扩展对象code:

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

这篇关于如何ViewBag在ASP.NET MVC的作品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆