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

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

问题描述

我有一个很难解决与MVC视图以下。

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

我的目标是在一个MVC视图中显示来自多个表中的数据。的数据的大部分来自一个称为零售商表。我也有存储从零售商表retailerid,并链接到一个类别表中的类别id另一个表称为RetailerCategories。

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表中的每个retailerid多条记录。

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.

什么是完成这一任务的最佳方式?一些我曾尝试都覆盖在的事情你能用这个MVC帮助视图模型问题?

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.

这句话其实是非常好的,因为它解释正是你需要的。所以,一旦你知道你需要什么继续和modelize吧:

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&LT; RetailerViewModel&GT; 。从这里很容易peasy做你在视图中想要什么:

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天全站免登陆