Dynamic view of anonymous type missing member issue - MVC3

前端 未结 6 2027
春和景丽
春和景丽 2021-02-06 17:50

I have an MVC3 site that I\'ve setup for testing another site - most of it has been quick and dirty, and so I\'ve not gone to town creating model and view model types for all th

6条回答
  •  醉梦人生
    2021-02-06 18:54

    I think ToSafeDynamic is a good solution. But I'd like to share some other options using the open source ImpromptuInterface (in nuget) that would work well in this situation.

    One option, being a DynamicObject based proxy, ImpromptuGet which will just forward calls to the annonymous type, similar to using dynamic (it uses the same api's except it sets the context to the anonymous type's self so the internal access doesn't matter).

    ViewBag.SomeData = Enumerable.Range(1,10)
                               .Select(i => ImpromptuGet.Create(new { Value = i }));
    

    This option doesn't look as clean as ToSafeDynamic, but it has a small distinction in that it is only calling the properties when they are used, rather than copying all the data upfront.

    However, a better solution from ImpromptuInterface is it's quick syntax for creating prototype dynamic objects.

    ViewBag.SomeData = Enumerable.Range(1,10).Select(i => Build.NewObject(Value:i));
    

    that will create an expando-like object, but you also have the option to create literal ExpandoObjects (which in my testing offer the same performance on getters as POCO objects cast to dynamic).

    ViewBag.SomeData = Enumerable.Range(1,10)
                               .Select(i => Build.NewObject(Value:i));
    

    Also the creation setup portion can be stored in a temporary variable or fields to shorten the lambda even more.

    var Expando =Build.NewObject;
    ViewBag.SomeData = Enumerable.Range(1,10).Select(i => Expando(Value:i));
    

提交回复
热议问题