首页 > 解决方案 > 在同一页面上显示来自 ASP.NET MVC 5 中 2 个表的数据

问题描述

我正在使用带有 C# 的 ASP.NET MVC 进行 Web 开发。我想创建一个动态网站。我创建了一个带有 2 个表的数据库 DATABASE

我创建模型视图以在同一页面中显示两个表中的数据

public class HomeViewModel
{
    public IEnumerable<Product> product { get; set; }
    public IEnumerable<Company> company { get; set; }
}

如何id==1在同一主页上显示第一个产品 ( ) 和所有公司?

注意:我使用 ASP.NET MVC 和 C#(不是 ASP.NET Core MVC)

标签: c#asp.netasp.net-mvc-5

解决方案


使用这样的视图模型:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Company
{
    public int Id { get; set; }
    public string Desc { get; set; }
}

public class HomeViewModel
{
    public IEnumerable<Product> Products { get; set; }
    public IEnumerable<Company> Companies { get; set; }
}

第一个产品和所有公司的简单剃须刀标记可以如下所示:

@model HomeViewModel

<h1>Products</h1>
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Products.Take(1))
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.Name</td>
            </tr>
        }
    </tbody>
</table>

<h1>Companies</h1>
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Desc</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Companies)
        {
            <tr>
                <td>@item.Id</td>
                <td>@item.Desc</td>
            </tr>
        }
    </tbody>
</table>

推荐阅读