I am refactoring an MVC 3 application, and moved a set of similar items into a partial view so I can keep that template DRY. Since the pieces don't all have the exact same properties, I am creating anonymous types like this:
var model1 = new { Description = "description 1", Message = "message 1" }
and passing them to the partial view like so:
@Html.Partial("_Partial", model1)
The partial view is then attempting to render certain blocks based on existence of a specific property, i.e.
@if (Model.Description != null)
{
@Model.Description
}
My issue is that even though I can see and navigate the Model
object in the watch window during execution, I get a RuntimeBinderException
in the if
test that states 'object' does not contain a definition for 'ShowApplied'
. I can obtain the values through reflection by calling (Model.GetType().GetProperty("ShowApplied").GetValue(Model)
), but would much rather use the format shown in my code sample. I have been unable to find a clean solution...
- How can I pass an anonymously-typed object to a partial view and access its properties directly? I feel like there is something simple I'm missing...
- Why am I able to see the
Model
properties while debugging, but not access them from code?
EDIT
- I am specifying @model dynamic.
- Using an interface requires creating non-anonymous types because, as this answer explains,
An anonymous type cannot be cast to any interface or type except for
object
.