It's not just that, but with dynamic support you can also declare your own objects to act as dynamic objects by implementing IDynamicMetaObjectProvider or -- as a shortcut -- by extending DynamicObject. Both types exist in the namespace System.Dynamic.
There's also a very famous type called ExpandoObject.
ExpandoObject is a dynamic object that you can simply create properties on it at runtime.
Now the trick that I want to use, is to declare my views to extend the generic System.Web.Mvc.ViewPage
Here's a code example:
using System.Dynamic; using System.Web.Mvc; public class ArticlesController : Controller { public ViewResult Index() { dynamic x = new ExpandoObject(); x.Title = "Programming for Cowards"; x.Url = "http://galilyou.blogspot.com"; //I even can nest x.Author = new ExpandoObject(); x.Author.Name = "Galilyou"; return View(x); } }In the above code I declare an ExpandoObject and start to set some properties on it like Title, Url, etc.
I do this by simply using the syntax var.Property = value; which will automagically create a property on the dynamically created object which type will be the type of value.
If you look closely you would notice that the Author property is an ExpandoObject itself. This nesting is allowed to as many levels as you want.
Here's how my view looks like:
< %@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
Note, the view is declared to extend System.Web.Mvc.ViewPage
Now you can use the values of the model like so:
And here's the page after running the application:
Disclaimer:
You shouldn't do this in a large scale application. View model objects are still the best tool for the job when the application grows. However, if you want to quirk something pretty quickly -- a small thing-- you might get away with that.
Model.Url Model.Title Model.Author.Namehere's how the entire view will look like:
And here's the page after running the application:
Disclaimer:
You shouldn't do this in a large scale application. View model objects are still the best tool for the job when the application grows. However, if you want to quirk something pretty quickly -- a small thing-- you might get away with that.
Hope this helps.
3 comments:
hi
U really opened a interesting site.
I am also a dot net programmer.
currently my blog is http://www.itblog2100.blogspot.com
follow me in my blog then i will to keep in touch.
It is a nice helpful blog.
Thanks
mirror from brandshowrooms.com
BrandShowRooms.com
Nice post about the Expando object. There are not too many actual useful blogs out there talking about it.
My latest blog post (and following articles) will touch on taking Dynamics past the cookie cutter functionality. Feel free to drop in and say hi!
http://digg.com/programming/Building_a_better_dynamic_NET_4_0
Post a Comment