剃刀模板中的动态类型列表
// this function working perfectly
public dynamic CountTable()
{
return (from t in db.Users
group t by t.Type into g
select new
{
type = g.Key,
count = g.Count(),
ActiveGroups = (from t in g group t by t.Active into ag select new { active = ag.Key, count = ag.Count() })
}).ToList();
}
// and this loop working in MVC Controller
foreach (dynamic uct in ur.CountTable())
{
int x = uct.count;
}
但在模板中不起作用:
Line 12: @foreach (dynamic uct in ViewBag.ur.CountTable())
Line 13: {
Line 14: int adet = uct.count;
Line 15: }
第 14 行:“对象”不包含“计数”的定义
为什么?我能做些什么?
// this function working perfectly
public dynamic CountTable()
{
return (from t in db.Users
group t by t.Type into g
select new
{
type = g.Key,
count = g.Count(),
ActiveGroups = (from t in g group t by t.Active into ag select new { active = ag.Key, count = ag.Count() })
}).ToList();
}
// and this loop working in MVC Controller
foreach (dynamic uct in ur.CountTable())
{
int x = uct.count;
}
But not working in template:
Line 12: @foreach (dynamic uct in ViewBag.ur.CountTable())
Line 13: {
Line 14: int adet = uct.count;
Line 15: }
Line 14: 'object' does not contain a definition for 'count'
Why? What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
匿名类型被编译成内部类。
dynamic
使用的标准绑定器将仅绑定到公共类的公共成员。因此,您不能将其与来自不同程序集的匿名类型一起使用。
有关详细信息,请参阅 此处。
Anonymous types are compiled into internal classes.
The standard binder used by
dynamic
will only bind to public members of public classes.Therefore, you cannot use it with anonymous types from a different assembly.
For more information, see here.
不能肯定地说,因为我从不使用动态,但我怀疑这是剃刀视图引擎不支持的情况。尽管您可以拥有动态模型并直接调用其属性。例如,以下内容有效:
但如果我们将其移至其他地方的某个静态方法中:
它不再有效,因为我怀疑 razor 会自动转换为对象。
我建议您定义几种类型并使用强类型,而不是使用动态。
Cannot say for sure as I never use dynamic but I suspect that this is a situation which is not supported by the razor view engine. Although you can have a dynamic model and directly invoke properties on it.For example the following works:
but if we move this into some static method somewhere else:
it no longer works as I suspect razor converts automatically to object.
Instead of using dynamic I would recommend you defining a couple of types and work with strong types.