且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在单个 MVC 视图中显示来自多个表的数据

更新时间:2023-09-16 12:57:34

您需要一个专门针对此视图需求定制的视图模型.在定义视图模型时,您不应该考虑表格.SQL 表在视图中完全没有意义.考虑您需要显示哪些信息并相应地定义您的视图模型.然后你可以使用 AutoMapper 在你的真实模型和你定义的视图模型之间进行转换.

You need a view model specifically tailored to the needs of this view. When defining your view models you shouldn't be thinking in terms of tables. SQL tables have absolutely no meaning in a view. Think in terms of what information you need to show and define your view models accordingly. Then you could use AutoMapper to convert between your real models and the view model you have defined.

所以忘记你所说的关于表格的所有内容,专注于以下句子:

So forget about all you said about tables and focus on the following sentence:

在视图中我想显示一个列表零售商和每个零售商我想要显示类别列表适用于他们.

In the view I want to show a list of retailers and with each retailer I want to show the list of categories applicable to them.

这句话实际上非常好,因为它准确地说明了您的需求.因此,一旦您知道自己需要什么,就可以对其进行建模:

This sentence is actually very good as it explains exactly what you need. So once you know what you need go ahead and modelize it:

public class CategoryViewModel
{
    public string Name { get; set; }
}

public class RetailerViewModel
{
    public IEnumerable<CategoryViewModel> Categories { get; set; }
}

现在您将视图强输入到 IEnumerable.从这里开始,您可以轻松地在视图中执行您想要的操作:

Now you strongly type your view to IEnumerable<RetailerViewModel>. From here it is easy-peasy to do what you want in the view:

显示零售商列表,每个零售都有关联类别列表.

showing a list of retailers with each retail having a list of associated categories.