Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Thursday, July 28, 2011

How to pass Dynamic Anonymous Object to ViewPage in Razor

Normally, you can't pass anonymous object as a model to ViewPage because it can only be accessed from within the assembly in which it’s declared. Since views get compiled separately, the dynamic binder complains that it can’t go over that assembly boundary. So, to solve this problem we have to create own ViewPage that use dynamic object as a Model, or create extension method to change its type to ExpandoObject.

Using ExpandoObject:
public static ExpandoObject ToExpando(this object anonymousObject)
{
    IDictionary anonymousDictionary =
    HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
    IDictionary expando = new ExpandoObject();
    foreach (var item in anonymousDictionary)
        expando.Add(item);
    return (ExpandoObject)expando;
}

Then, you can pass anonymous object through Model, and use it as dynamic object.
References: http://stackoverflow.com/questions/5120317/dynamic-anonymous-type-in-razor-causes-runtimebinderexception, http://blogs.msdn.com/b/davidebb/archive/2009/12/18/passing-anonymous-objects-to-mvc-views-and-accessing-them-using-dynamic.aspx

No comments:

Post a Comment