How ViewBag in ASP.NET MVC works

前端 未结 7 1982
清酒与你
清酒与你 2020-11-28 04:38

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.F

7条回答
  •  有刺的猬
    2020-11-28 05:00

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

    It is declared like this:

    dynamic ViewBag = new System.Dynamic.ExpandoObject();

    which is why you can do :

    ViewBag.Foo = "Bar";

    A Sample Expander Object Code:

    public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
    {
        public Dictionary objectDictionary;
    
        public ExpanderObject()
        {
            objectDictionary = new Dictionary();
        }
        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;
            }
        }
    }
    

提交回复
热议问题