问题
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
.
回答1:
Insights from the comments (thank you) imply I have 2 options, since (as the answer to the linked question points out),
Anonymous types are internal, so their properties can't be seen outside their defining assembly.
and therefore are inaccessible to the Razor binding engine.
Use
@Html.DisplayFor("amount")
and deal with not having IntelliSense, reference lookups, etc.Create classes that implement a common interface and bind my partial view to that interface.
来源:https://stackoverflow.com/questions/30583686/pass-anonymous-type-as-model-in-mvc-3-partial-view