【问题标题】:dynamic typed list in razor template剃刀模板中的动态类型列表
【发布时间】:2011-04-06 14:56:13
【问题描述】:
// 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 行:“object”不包含“count”的定义

为什么?我能做什么?

【问题讨论】:

    标签: linq asp.net-mvc-3 dynamic c#-4.0 razor


    【解决方案1】:

    匿名类型被编译成内部类。

    dynamic 使用的标准绑定器只会绑定到公共类的公共成员。
    因此,您不能将它与来自不同程序集的匿名类型一起使用。

    有关详细信息,请参阅here

    【讨论】:

      【解决方案2】:

      不能肯定地说,因为我从不使用动态,但我怀疑这是剃刀视图引擎不支持的情况。尽管您可以拥有一个动态模型并直接在其上调用属性。

      例如以下作品:

      @foreach (dynamic uct in new[] { new { Name = "foo" } })
      {
          <div>@uct.Name</div>
      }
      

      但是如果我们将它移到其他地方的某个静态方法中:

      @foreach (dynamic uct in Foo.SomeStaticMethod())
      {
          <div>@uct.Name</div>
      }
      

      它不再起作用,因为我怀疑 razor 会自动转换为对象。

      我建议您定义几个类型并使用强类型,而不是使用动态类型。

      【讨论】:

      • @SLaks,正确,您的回答很好地解释了它。感谢您指出了这一点。它消除了我的困惑。我将更新我的答案,只保留不使用动态的相关部分。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多