Ang3lFir3 – Life as a Code Poet

January 25, 2011

ExpandoObject and Views

This sample was spawned by a comment made by my friend and co-worker Bobby Johnson (@NotMyself) . I can’t remember exactly what he said but it had something to do with dynamic and views. (maybe he will tell us in the comments :-) )

Let me first say that many of the projects at work on built on MonoRail which is often considered to be the predecessor to ASP.Net MVC and as such we don’t get a huge amount of exposure to the new toys in ASP.Net MVC immediately.

With that out of the way I was getting prepared to write this post and I just happened to notice that ASP.Net MVC views in .Net 4.0 projects seem to all be of type System.Data.ViewPage<dynamic> , which got me super excited! This makes things even easier!

So here goes a super simple example ….

The Controller :

    public class SampleController : Controller
    {
        public ActionResult Index()
        {
            dynamic viewModel = new ExpandoObject();
            viewModel.Name = "We Named this thing";
            viewModel.SomeInts = new[]{1,2,3};
            viewModel.AMethod = (Func<string>) (() => "This is a sample function implementation");
            return View(viewModel);
        }
    }

The View :

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Index</title>
</head>
<% var viewModel = ViewData.Model; %>
<body>
    <div>
        <span>First Property value : <%= viewModel.Name %></span> <br />
        <span>Second Property value :  <%= viewModel.SomeInts.Length %></span><br />
        <span>A Sample Method Impl : <%= ((Func<string>) viewModel.AMethod)()%></span>
    </div>
</body>
</html>

Crazy huh? yeah I thought so too. This is great news for those times when you need to send some calculated data to the view but you don’t exactly want to run off and build a custom view type.

Ok some NUnit tests this time. Not exactly the best tests, but they should help prove it does work.

The Test :

    [TestFixture]
    public class preseneters_with_dynamic_viewdata
    {
        [Test]
        public void make_sure_you_can_test_them()
        {
            var controller = new SampleController();
            var result = controller.Index() as ViewResult;

            dynamic dynamicModel = result.ViewData.Model;

            Assert.AreEqual("We Named this thing",dynamicModel.Name);
            Assert.AreEqual(3,dynamicModel.SomeInts.Length);
            Assert.AreEqual("This is a sample function implementation",((Func<string>)dynamicModel.AMethod)());
        }
    }

Thanks for reading please leave comments, ideas, corrections, and hate mail in the comments section below.

About these ads

9 Comments »

  1. Not sure if you’re using ASP.NET MVC3, but they have this built in with the “ViewBag”. Otherwise, I think this idea was the driver for adding the ViewBag to MVC3 if you’re using MVC1 or 2.

    Check out Scott Gu’s post when the RC came out

    Great post though, good to see how to add and call methods on a dynamic object in a view.

    Comment by eric b — April 10, 2011 @ 6:23 am

    • Actually this was with MVC3… however I hadn’t yet seen the ViewBag yet….

      I agree with you tho that I believe this concept was the driver behind the ViewBag ….

      Comment by ang3lfir3 — April 11, 2011 @ 6:48 am

  2. Great post. Will try that in my own website.

    Comment by Shekhar Agarwal — April 10, 2011 @ 7:24 pm

  3. Hi,

    Article is very nice except one small bug. Please correct that.

    Code in View:

    This throws error at runtime.
    ‘object’ does not contain a definition for ‘Name’

    Working code:

    Thanks,
    Thani

    Comment by Thanigainathan — April 10, 2011 @ 8:54 pm

  4. Hi,

    sorry code did not appear because of angle percentage

    Code in View:
    var viewModel = ViewData.Model;

    This throws error at runtime.
    ‘object’ does not contain a definition for ‘Name’

    Working code:
    Import Namespace=”System.Dynamic”
    dynamic viewModel = ViewData.Model;

    Thanks,
    Thani

    Comment by Thanigainathan — April 10, 2011 @ 8:56 pm

    • thanks for spotting that. I’m guessing it came from me refactoring on the spot and forgetting that var doesn’t work with dynamic….

      or I could claim I put it there intentionally to keep people on their toes. :)

      Comment by ang3lfir3 — April 11, 2011 @ 6:46 am

      • Thanks Eric

        Comment by Thanigainathan — April 11, 2011 @ 10:36 am

      • Hi,
        change this line Inherits=”System.Web.Mvc.ViewPage”

        to Inherits=”System.Web.Mvc.ViewPage”

        cheers

        Comment by Parminder — April 11, 2011 @ 6:58 pm

      • Hi,
        change this line Inherits=”System.Web.Mvc.ViewPage”

        to Inherits=”System.Web.Mvc.ViewPage”

        My mistake, sorry.

        cheers

        Comment by Parminder — April 11, 2011 @ 7:58 pm


RSS feed for comments on this post. TrackBack URI

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

The Silver is the New Black Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: