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
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 ExpandoObject
s (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));