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.