Pass anonymous type as model in MVC 3 Partial View

耗尽温柔 提交于 2020-01-06 02:53:09

问题


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...

  1. 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...
  2. 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.

  1. Use @Html.DisplayFor("amount") and deal with not having IntelliSense, reference lookups, etc.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!