Exemplo n.º 1
0
        protected virtual ActionResult Dynamic(ControllerBase controller, string viewName, object model, Func <ControllerBase, Dictionary <string, object>, string, object, object> json)
        {
            var propertyBag = new Dictionary <string, object>();

            if (model != null)
            {
                List <JsonField> properties;
                var cacheKey = model.GetType().FullName;

                if (!_propertyCache.TryGet(cacheKey, out properties))
                {
                    properties = new List <JsonField>();
                    properties.AddRange(model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                        .Where(property => GetCustomAttribute(property, typeof(JsonPropertyAttribute)) != null)
                                        .Select(property => new JsonField(property, (JsonPropertyAttribute)GetCustomAttribute(property, typeof(JsonPropertyAttribute))))
                                        .ToList());
                    properties.AddRange(model.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                                        .Where(field => GetCustomAttribute(field, typeof(JsonPropertyAttribute)) != null)
                                        .Select(field => new JsonField(field, (JsonPropertyAttribute)GetCustomAttribute(field, typeof(JsonPropertyAttribute))))
                                        .ToList());

                    _propertyCache.Add(cacheKey, properties);
                }

                properties.ForEach(property => propertyBag.Add(property.Name, property.GetValue(model)));
            }

            return(controller.AsDynamic().Json(json(controller, propertyBag, viewName, model), JsonRequestBehavior.AllowGet));
        }