如何在单个 MVC 视图中显示来自多个表的数据 [英] How do I display data from multiple tables in a single MVC view

查看:24
本文介绍了如何在单个 MVC 视图中显示来自多个表的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用 MVC 视图解决以下问题.

I am having a hard time solving the following with an MVC view.

我的目标是在单个 MVC 视图中显示来自多个表的数据.大部分数据来自名为零售商"的表.我还有另一个表,称为 RetailerCategories,它存储来自 Retailers 表的retailid 以及链接到 Category 表的 categoryid.

My goal is to display data from multiple tables in a single MVC view. The bulk of the data comes from a table called Retailers. I also have another table called RetailerCategories which stores the retailerid from the Retailers table and also a categoryid linking to a Category table.

请注意,RetailerCategories 表中的每个零售商 ID 都有多个记录.

Note that there are multiple records for each retailerid in the RetailerCategories table.

在视图中,我想显示一个零售商列表,我想显示每个零售商的适用类别列表.

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.

实现这一目标的最佳方法是什么?我尝试过的一些事情在 你能帮助这个 MVCViewModel 问题?

What would be the best way to accomplish this? Some of the things I have tried are covered in Can you help with this MVC ViewModel issue?

然而,这似乎不是正确的方法.

This however does not appear to be the right approach.

推荐答案

您需要一个专门针对此视图需求定制的视图模型.在定义视图模型时,您不应该考虑表格.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.

这篇关于如何在单个 MVC 视图中显示来自多个表的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆