gpt4 book ai didi

asp.net-mvc - 如何在单个 MVC View 中显示多个表中的数据

转载 作者:行者123 更新时间:2023-12-01 22:56:29 25 4
gpt4 key购买 nike

我很难用 MVC View 解决以下问题。

我的目标是在单个 MVC View 中显示多个表中的数据。大部分数据来自名为 Retailers 的表。我还有另一个名为 RetailerCategories 的表,它存储 Retailers 表中的 Retailerid 以及链接到 Category 表的 CategoryID。

请注意,RetailerCategories 表中每个 Retailerid 有多个记录。

在 View 中,我想显示零售商列表,并且对于每个零售商,我想显示适用于他们的类别列表。

实现这一目标的最佳方法是什么?我尝试过的一些事情在Can you help with this MVC ViewModel issue?中有介绍。

但这似乎不是正确的方法。

最佳答案

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

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

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.

这句话其实很好,它准确地解释了你需要什么。因此,一旦您知道需要什么,就可以对其进行建模:

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

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

现在您将您的 View 强式键入 IEnumerable<RetailerViewModel> 。从这里可以轻松地在 View 中执行您想要的操作:

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

关于asp.net-mvc - 如何在单个 MVC View 中显示多个表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4319488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com