Search code examples
asp.net-mvc-3razor

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'

Why do I see this error?
When I watch the Model object in debugging mode it looks all right (having 2 properties: Products and Threshold)


Solution

  • 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" });
    

    David Ebbo clarified that 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. Due to this forum post, David Ebbo clarified on (Dec 22 2011) that MVC 3 now has direct support for dynamic.