Razor view anonymous models

I stumbled across this issue this morning…

'object' does not contain a definition for 'Error'

Description: An unhandled exception occurred.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Error'

@if (Model != null) {@Model.Error}

Basically the anonymous type on the model is internal and can only be accessed by the assembly in which it is declared. Views get compiled separately and therefore can’t access the property.

How to fix it…

I found a nice little extension class referenced on stackoverflow


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

You then create your (very basic) anonymous model as follows:


const string error = "error message";

return View("viewname", new {Error = error}.ToExpando());

The razor view code is then as before:

@if (Model != null) {@Model.Error}