MVC剃刀动态模型,“对象”不包含“属性名”的定义 [英] MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName'

查看:129
本文介绍了MVC剃刀动态模型,“对象”不包含“属性名”的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MVC 3的Razor视图引擎。
我有这样的观点:

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();
}

据使用此code另一种观点叫做:

It is called from another view using this code:

@Html.Partial("PartialViewName", new { Products = Model, Threshold = 5 })

在这两种观点,当我调试他们和手表的型号,它似乎包含正确的对象。
当我执行code我得到了一个错误变种产品=行说:

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:

对象不包含定义为产品

任何人都可以向我解释为什么我得到这个错误?
同样,当我看Model对象在调试模式下,它看上去一切正常(有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:

据<一个href=\"http://blogs.msdn.com/b/davidebb/archive/2009/12/18/passing-anonymous-objects-to-mvc-views-and-accessing-them-using-dynamic.aspx\">David Ebbo ,你不能传递一个匿名类型分为动态类型的观点,因为匿名类型编译为内部。由于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:

大卫Ebbo编辑了他的职位与此澄清:

David Ebbo has edited his post with this clarification:

注(2011年12月22日):现在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剃刀动态模型,“对象”不包含“属性名”的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆