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

Using MVC 3 with Razor view engine. I have this View:

@model dynamic
@{
    var products = (List<ListItemBaseModel>)Model.Products;
    var threshold = (int)(Model.Threshold ?? 1);
    var id = Guid.NewGuid().ToString();
}

It is called from another view using this code:

@Html.Partial("PartialViewName", new { Products = Model, Threshold = 5 })

In both Views, when i debug them and watch Model, it seems to contain the correct object. When i execute the code i get an error on the "var products =" line saying:

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

Can anyone explain to me why i get that error? Again, when i watch the Model object in debugging mode it looks all right (having 2 properties: Products and Threshold)


Solution 1:

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!

Solution 2:

On .NET 4.0 Anonymous types can easily be converted to ExpandoObjects and thus all the problems are fixed with the overhead of the conversion itself. Check out here