将模型中的数据合并到一个foreach循环中?

时间:2016-05-16 12:21:01

标签: asp.net-mvc

是否可以使用下面代码中的foreach loop之外的其他解决方案,以便只能在WeeksWeekNamesShort标记中获取td<td> @week @monthName </td>列表中的值像这样:td而不是使用两个单独的public IEnumerable<int> Weeks { get; set; } public IEnumerable<string> WeekNamesShort { get; set; } 标签?

模型的一部分:

<tr>
<td></td>              
@foreach (var week in project.Weeks)
{
    <th class="week" data-week="@week">@week</th>
}
</tr>
<tr>
<td></td>
@foreach (var monthName in project.WeekNamesShort)
{
   <td class="week">@monthName</td>
}
</tr>

视图中的部分代码:

db.collection.aggregate([    
    { 
        "$group": { 
            "_id": "$_id",             
            "activity_active": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$segment.activity", "active" ] }, 1, 0 ]
                }
            },
            "activity_inactive": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$segment.activity", "inactive" ] }, 1, 0 ]
                }
            },
            "activation_active": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$segment.activation", "active" ] }, 1, 0 ]
                }
            },
            "activation_inactive": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$segment.activity", "inactive" ] }, 1, 0 ]
                }
            },
            "plan_free": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$segment.plan", "free" ] }, 1, 0 ]
                }
            } 
        }  
    },
    {
        "$project": {
            "_id": 0,            
            "activity": {
                "active": "$activity_active",
                "inactive": "$activity_inactive"
            },
            "activation": {
                "active": "$activation_active",
                "inactive": "$activation_inactive"
            },
            "plan": {
                "free": "$plan_free"
            }
        }
    }
])

2 个答案:

答案 0 :(得分:3)

您可以调整视图模型以符合视图的要求:

public class WeekViewModel
{
    public int Number { get; set; }
    public string Name { get; set; }
}

然后拥有IEnumerable<WeekViewModel>属性:

public IEnumerable<WeekViewModel> Weeks { get; set; }

然后你可以循环:

@foreach (var week in project.Weeks)
{
   <td class="week">
       @week.Number
       @week.Name
   </td>
}

答案 1 :(得分:0)

如果要保留相同的视图模型,可以使用for循环和LINQ扩展ElementAt

@for(var i = 0; i < 7; i++)
{
   <td class="week">
       @Model.Weeks.ElementAt(i)
       @Model.WeekNamesShort.ElementAt(i)
   </td>
}