我已经创建了我的数据库 .
我的数据库“Categories”和“Contents”中有两个表 .
我的"Categories"表包含: Id, CategoryName . 我的"Contents"表包含: Id, Link, Category .
Id, CategoryName
Id, Link, Category
我希望在MVC Razor的单个视图中显示这两个表 .
我要在每个视图中显示一个表,但是我无法在视图中显示两个表 . 有人可以一步一步地教我如何做到这一点吗?
我不想显示硬编码列表详细信息 .
您可以创建一个ViewModel,如:
public class MyViewModel { public List<Category> Categories {get; set;} public List<Content> Contents {get; set;} }
使用Controller Action中的数据填充ViewModel:
public ActionResult Index() { var vm = new MyViewModel(); vm.Categories = db.GetCategories(); vm.Contents = db.GetContents(); return View(vm); }
在您的相应视图中:
@model MyApp.Models.MyViewModel
您现在可以在视图中的任何位置使用 @Model 来遍历来自2个来源的数据 .
@Model
选择正确的强类型模型 . 此模型将包含“类别”和“内容”详细信息 .
在您的视图中创建两个HTML表格,例如
<div> <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> ... </tr> </thead> <tbody> @foreach( var category in Model.Categories ) { <tr> <td>@category.detail1</td> <td>@category.detail2</td> ... </tr> } </tbody> </table> </div>
您可以根据需要创建任意数量的这些 . 使用CSS引用外部 <div> 样式并将表格放在屏幕上
<div>
2 回答
您可以创建一个ViewModel,如:
使用Controller Action中的数据填充ViewModel:
在您的相应视图中:
您现在可以在视图中的任何位置使用
@Model
来遍历来自2个来源的数据 .选择正确的强类型模型 . 此模型将包含“类别”和“内容”详细信息 .
在您的视图中创建两个HTML表格,例如
您可以根据需要创建任意数量的这些 . 使用CSS引用外部
<div>
样式并将表格放在屏幕上