‘object’ does not contain definition for ‘PropertyName’ when using Razor and dynamic objects

Posted by Matheus Guimaraes |11 Mar 14 |

If you are trying to pass anonymous dynamic objects to a Razor view you will run into this error. That is because as of C# 5.0 anonymous dynamic objects are compiled as internal.

Considering that views are compiled into a completely separate assembly from controllers, by the time your view model is reaching Razor it just simply won’t have visibility of it, reason why you get the error. so in a nutshell, for now:

Dynamic anonymous objects are not supported by the default MVC engine. 

you can always hack around it by doing casts to ExpandoObject and other tricks, however, my recommendation is to change your code to use a named class so you’re not putting in workarounds which may (and probably and hopefully will) become obsolete with future versions for the framework.