I’ve come across this strange issue and decided to blog about it since I can’t figure out exactly why this is happening it is clearly something to do with the DLR and interfaces.
First, if you are getting the exception: 'object' does not contain a definition for 'xxxx' it is related to either an object you have being marked internal or you are are using an anonymous object type for your model (which .Net will always mark as internal).
Here’s a really easy way to replicate this:
1. Create an internal model
2. Return this model in your MVC action
3. Make your view have a dynamic model and then try to render the model’s property
You’ll get the exception:
Server Error in '/' Application.
'object' does not contain a definition for 'Name'
So even though the error is not very informative, it makes sense since Razor is trying to access an internal class.
Try using a public interface
Ok so if we want to keep our class internal, we could expose it via a public interface. Our code might then look like this:
Then we can change our view to be strongly typed like:
And it will work, however if you change your view back to be @model dynamic you will still get the exception. Pretty sure it’s because the DLR is just binding to the instance object and doesn’t really care about the interface… this makes sense.
Try using an abstract public class
For some reason if you make your internal class inherit from a public abstract class that implements the same interface you will not get this exception even though the object instance you are passing to razor is internal. For example with this structure:
You will not get this error if your view is @model dynamic.
I’m sure there’s something written in the DLR spec about this but still seems strange to me! If you are getting this error and you aren’t using anonymous objects for your model, hopefully this might help you figure out what is going on.