【问题标题】:Looping inside razor在剃须刀内循环
【发布时间】:2014-09-23 07:11:52
【问题描述】:

我为每个控件分配了字段名称“GroupTitle”。我想遍历分配给特定组的 Control 的每个元素。

public class Groups
{
    public virtual int Id { get; set; }
    public virtual string GroupTitle { get; set; }

}

public class Controls
{
    public int Id { get; set; } //Id
    public string Name { get; set; } //name of control/element
    public string ControlType { get; set; }  // checkbox, radio button, textbox, time, date
    public string Caption { get; set; } //caption/title/label        
    public string Content { get; set; } //in case of checkbox        
    public bool Mandatory { get; set; } //is mandatory to select or enter its value.                 
    public string GroupTitle { get; set; } // there will be title at the top of controls if grouped together                

    //public List<SelectListItem> SelectOptions { get; set; } //select/dropdown options e.g. Pakistan, Uk for country dropdown        

}

下面是我的代码。我不确定如何在嵌套循环中访问模型变量。这给了我错误。它还给我错误,即 Where 子句不存在。

@foreach (var groups in Model.Groups)
{                                                    
    foreach (var row in Model.Controls.Where("GroupTitle ==",  @groups.GroupTitle;))
    {   

    }
}

【问题讨论】:

  • 您能向我们解释一下您要达到的目标吗?
  • 请看我修改后的帖子。
  • 我想你的意思可能是foreach(var row in Model.Controls.Where(r =&gt; r.GroupTitle == groups.GroupTitle));
  • 是的,但这给了我错误不能使用 lambda 表达式作为动态调度操作的参数

标签: asp.net-mvc-4 razor


【解决方案1】:

证明这一点:

@foreach (var groups in Model.Groups)
{                                                    
    foreach (var row in Model.Controls.ToList().Where(x => x.GroupTitle == groups.GroupTitle))
    {   

    }
}

我认为this answers 可能也适用于您的情况。

【讨论】:

  • 我收到错误 Lambda 表达式作为动态分派操作的参数
  • 这可能是因为 Controls 是 IQueryable。我更新了答案以将其转换为列表。
  • 为了测试您建议的链接,我使用了这个语句 @{ var layers = from p in Model.Controls where p.GroupTitle = "GroupTitle" select p; } 但它给了我错误 Query expressions over source type 'dynamic' or with a join sequence of type 'dynamic' are not allowed
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多