c# - 在同一页面上显示来自 ASP.NET MVC 5 中 2 个表的数据
问题描述
我正在使用带有 C# 的 ASP.NET MVC 进行 Web 开发。我想创建一个动态网站。我创建了一个带有 2 个表的数据库 DATABASE
- 产品(ID、名称)
- 公司 (id, desc)
我创建模型视图以在同一页面中显示两个表中的数据
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)
解决方案
使用这样的视图模型:
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>
推荐阅读
- javascript - 如果使用 Javascript 将图像 URL 设置为 div 背景,则图像 URL 不起作用
- android - 解压时找不到文件错误
- python - MySQLdb - ModuleNotFoundError
- angular - 如何将 ngrx-effect 中的 Action.payload 传播到 catchError 或 map 运算符?
- javascript - 函数返回未定义,应该返回承诺或值
- python - pytest布局导入不兼容
- bash - 远程主机、本地脚本、错误文件描述符
- r - DT::dataTable 搜索栏中的占位符
- jquery - 进度条居中文本
- oracle-apex - 如何在移动应用程序的 oracle apex 中删除桌面主题