循环使用Razor中的模型内容

时间:2012-10-25 23:06:11

标签: c# asp.net-mvc asp.net-mvc-4 razor

我想在剃须刀视图中循环浏览模型中的每个项目,但我想将所有项目组合在一起。然后我想循环遍历每个组。想象一下,我有一张桌子:

ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56

我想做类似的事情:

@foreach (var group in Model.GroupNo) {
    <section>
        <header>Group No is @group.GroupNo</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 

所以我的输出是:

Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56

这可能吗?

由于

3 个答案:

答案 0 :(得分:28)

是的,使用Linq GroupBy很容易做到这一点。我建议更改您的观点以使用@model IEnumerable<IGrouping<string, MyModel>>,您可以这样填充:

var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);

然后,只需在编写时遍历该组,除了使用group.Key而不是group.GroupNo来检索IGrouping的密钥:

@foreach (var group in Model) {
    <section>
        <header>Group No is @group.Key</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 

答案 1 :(得分:10)

LINQ可以帮助你做到这一点

@model IEnumerable<Project1.Models.Group>


@foreach (var item in Model.Select(i=>i.groupno).Distinct().ToList()) {
    <tr>
        <td>
            <header>Group No is @item</header>
            @foreach (var grpName in Model.Where(i => i.groupno == item).ToList())
            {
                <p>GroupName: @grpName.groupName</p>
            }
        </td>
    </tr>
}

答案 2 :(得分:-4)

from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
import os
import unittest
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
from goodsRegister import goodsweb

EmailEntry = input("Please Enter Email Address: ")
password='12345678'
class checking(unittest.TestCase):

    def setUp(self):
        driverlocation = "/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
        os.environ["webdriver.chrome.driver"] = driverlocation
        self.driver= webdriver.Chrome(driverlocation)
        #self.driver= webdriver.Safari()

    def test_register(self):

    def tearDown(self):
        self.driver.close()

if __name__ =="__main__":
    unittest.main()