MVC Razor 动态模型,“对象"不包含“属性名称"的定义 [英] MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName'
问题描述
使用带有 Razor 视图引擎的 MVC 3.我有这个视图:
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 })
在两个视图中,当我调试它们并观察模型时,它似乎包含正确的对象.当我执行代码时,我在var products ="行上收到一条错误消息:
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'
谁能向我解释为什么我会收到那个错误?同样,当我在调试模式下观察模型对象时,它看起来没问题(有 2 个属性:产品和阈值)
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)
推荐答案
您是否将匿名类的实例作为视图模型传递?我刚刚尝试了这个(CSHTML 中的动态视图模型)并且在使用匿名类时遇到了与您相同的错误,但是如果我创建了一个命名类,它就可以正常工作.我搜索过,但在任何地方都没有看到这个记录.
Are you passing an instance of an anonymous class as the view model? I just tried this (dynamic view model in CSHTML) and got the same error as your when using an anonymous class, but it worked fine if I created a named class. I searched but haven't seen this documented anywhere.
// error
return View(new { Foo = 1, Bar = "test" });
// worked
return View(new TestClass { Foo = 1, Bar = "test" });
编辑 #1:
根据 David Ebbo 访问它们,您不能将匿名类型传递给动态类型因为匿名类型被编译为 internal
.由于 CSHTML 视图被编译成一个单独的程序集,它无法访问匿名类型的属性.
According to David Ebbo, you can't pass an anonymous type into a dynamically-typed view because the anonymous types are compiled as internal
. Since the CSHTML view is compiled into a separate assembly, it can't access the anonymous type's properties.
编辑#2:
David Ebbo 编辑了他的帖子,并进行了澄清:
David Ebbo has edited his post with this clarification:
注意 (12/22/2011):现在 MVC 3 直接支持动态,不再需要下面的技术.这篇文章实际上是导致将该功能集成到 MVC 的原因!
Note (12/22/2011): now that MVC 3 has direct support for dynamic, the technique below is no longer necessary. This post is in fact what led to integrating the feature into MVC!
这篇关于MVC Razor 动态模型,“对象"不包含“属性名称"的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!