MVC3 – Passing dynamic objects to views

In this post, I’ll explain how to pass a model with dynamic objects to a view.

If you are new to C# 4 features like dynamic objects, ExpandoObject etc I suggest to visit below links to get familliar with the concepts.

http://msdn.microsoft.com/en-us/library/dd264741.aspx

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

By using dynamic and ExpandoObject, you can pass a runtime object with some dynamic properties to a view and use them efficiently.

Controller Action
——————
——————

 public ActionResult DisplayDynamic()
{
      dynamic obj = new ExpandoObject();
      obj.FirstName = "Raj";
      obj.LastName = "Bandi";
      obj.Country = "Australia";

      return View("DynamicView", obj);
}

DynamicView.cshtml
————————
————————
//here I’m creating a simple view without any layout just to explain how to use the object

@model dynamic

  1. First Name: @Model.FirstName
  2. Last Name: @Model.LastName
  3. Country: @Model.Country

Demo
————–
—————
http://demos.rajbandi.net/mvc3/home/dynamic

Source Code
————-
————–

http://code.rajbandi.net/examples/mvc3/mvc3source.zip

Leave a Reply

Your email address will not be published. Required fields are marked *