MVC Razor dynamic model, ‘object’ does not contain definition for ‘PropertyName’

Are you passing an instance of an anonymous class as the view model? I just tried this (dynamic view model in CSHTML) and got the same error as your when using an anonymous class, but it worked fine if I created a named class. I searched but haven’t seen this documented anywhere.

// error
return View(new { Foo = 1, Bar = "test" });

// worked
return View(new TestClass { Foo = 1, Bar = "test" });

EDIT #1:

According to David Ebbo, you can’t pass an anonymous type into a dynamically-typed view because the anonymous types are compiled as internal. Since the CSHTML view is compiled into a separate assembly, it can’t access the anonymous type’s properties.

EDIT #2:

David Ebbo has edited his post with this clarification:

Note (12/22/2011): now that MVC 3 has direct support for dynamic, the technique below is no longer necessary. This post is in fact what led to integrating the feature into MVC!

Leave a Comment