C# dynamic ExpandoObject()

using System;
using System.Dynamic;
public class HomeController : Controller
{
       public ActionResult SingleObject()
       {
           dynamic contact = new ExpandoObject(); //Declaring new dynamic object

           contact.Name = "ABC"; // manually adding property & value
           string propertyName = "Age";  int propertyValue = 5; 
           AddProperty(contact, propertyName, propertyValue); //dynamically adding   
                                                                prop & value

           return View(contact);
       }

       //SingleObject.cshtml
       @model dynamic
       <h1>@Model.Name</h1>
       <h1>@Model.Age</h1>

       public ActionResult ObjectList()
       {
          // declaring a list of dynamic object
          dynamic contacts = new List<dynamic>(); 

          // Adding 1st object to the list
          contacts.Add(new ExpandoObject());
          contacts[0].Name = "ABC";
          contacts[0].Phone = "123";

          // Adding 2nd object to the list
          contacts.Add(new ExpandoObject());
          contacts[1].Name = "XYZ";
          contacts[1].Phone = "456";

          return View(contacts);
        }

        //ObjectList.cshtml
        @model dynamic
        @foreach (var item in Model)
        {
           <h2>@item.Name;</h2>
        }

        //Helper method to add property in run-time.
        public void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
        {
            // ExpandoObject supports IDictionary so we can extend it like this
            var expandoDict = expando as IDictionary<string, object>;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
        }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s