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)
I worked around this issue by using a Dictionary.
Instead of using the
dynamic
Model type within the partial view.You can call the anonymous object attributes using
@ViewData.Eval("foo")
instead of@Model.foo
.Then you can remove
@Model dynamic
from the view.I came across this issue recently when passing some attributes between views for the Facebook Social Comments Integration. Example code:
Then in my view I just had this div:
Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -
When you send the model to the view, convert it to Expando :
To use
dynamic
type you need to referenceMicrosoft.CSharp
assemblyOn .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
i am not sure that you are getting this error because you are not implementing the work-around. i got the same error in a partial view. the solution was just to clean the build and rebuild it. if the syntax is correct, the code should work, but the razor engine may not be updating the code changes properly.