通过匿名类型模型MVC 3管窥 [英] Pass anonymous type as model in MVC 3 Partial View
问题描述
我的重构MVC 3应用程序,搬到了一组类似物品的成局部视图,所以我可以保持该模板干燥。由于该件不都具有完全相同的特性,我创建匿名类型是这样的:
VAR模型1 =新的{说明=说明1,消息=消息1}
和它们传递到局部视图,像这样:
@ Html.Partial(_部分,MODEL1)
局部视图,然后尝试基于特定属性的存在使某些块,即
@if(Model.Description!= NULL)
{
@ Model.Description
}
我的问题是,即使我可以看到和执行过程中导航模式
对象在监视窗口,我收到了 RuntimeBinderException
在如果
试验,指出'对象'不包含'ShowApplied
的定义。我可以通过调用获得通过反射值( Model.GetType()的getProperty(ShowApplied)。的GetValue(模型)
),而宁愿使用格式显示在我的code样品。我一直无法找到一个干净的解决方案...
- 我怎么能传递一个匿名类型的对象的局部视图,并直接访问其属性?我觉得有一些简单的我失踪...
- 为什么我能看到,而调试
模式
的属性,而不是从code访问它们?
修改
- 我指定@model动态。
- 使用的接口需要创建非匿名类型,因为作为这个答案解释,
这是匿名类型不能转换为任何接口或类型,除了
对象
。
块引用>解决方案从注释洞察(谢谢)暗示我有2个选择,因为(作为答案的链接的问题指出)
匿名类型是内部的,因此它们的属性不能将其定义装配外面的人看见。
块引用>,因此无法进入剃刀绑定引擎。
使用
@ Html.DisplayFor(额)
和处理没有智能感知,参考查找等。创建实现一个共同的接口类和我绑定到该接口的局部视图。
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 aRuntimeBinderException
in theif
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
.
解决方案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.
这篇关于通过匿名类型模型MVC 3管窥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!