简体   繁体   English

MVC .NET C# - 从多个表中获取视图

[英]MVC .NET C# - Get View from multiple tables

I have about 4 tables from which I like to gather information and then show it in a view. 我有大约4张桌子,我喜欢收集信息,然后在视图中显示。 From my understanding, I would need to create a class in Model. 根据我的理解,我需要在Model中创建一个类。 In the Controller, I would then call that class. 在Controller中,我会调用该类。 I would then pass an instance of that class to the view. 然后我会将该类的实例传递给视图。

I am not sure though on how to do this programatically. 我不确定如何以编程方式执行此操作。 If some code can be provided as a simple example. 如果可以提供一些代码作为一个简单的例子。 Also I may need to edit and delete the records I show on the view as well. 此外,我可能还需要编辑和删除我在视图上显示的记录。

Do you already have the Data Access Layer up and running or how do you plan to read the data from the database and get it to the MVC application? 您是否已启动并运行数据访问层,或者您打算如何从数据库中读取数据并将其发送到MVC应用程序?

Are you planning to use SQL Server and Entity Framework or what? 您打算使用SQL Server和Entity Framework还是什么?

For general ideas on how to layer an ASP.NET MVC application see my answer here: MVC3 and Entity Framework in fact that answer applies to general architecture not only MVC but there are some comments below about how to split and keep separated various concerns. 关于如何分层ASP.NET MVC应用程序的一般想法请参阅我的答案: MVC3和实体框架实际上答案不仅适用于一般架构MVC,而且下面有一些关于如何分割和保持分离各种问题的评论。

Most of us are using a ORM like nhibernate or entity framework to handle data access. 我们大多数人都使用像nhibernate或实体框架这样的ORM来处理数据访问。 It makes everything strongly typed (if the mappings work OK ;)) and speeds up the development time. 它使所有强类型(如果映射工作正常;))并加快开发时间。

What you should do is to fetch your tables with a data access layer and use those to fill a view model with the information. 您应该做的是使用数据访问层获取表,并使用这些表用信息填充视图模型。 Something like: 就像是:

public ActionResult Details(int id)
{
    var user = _nhibernate.Get<User>(id);
    var company = _nhibernate.Get<Company>(user.CompanyId);
    var model = new DetailsModel{
       CompanyName = company.Name,
       UserName = user.Name
    };
    return View(model);
}

And the DetailsModel should be created in the WebProject\\Models folder. 应该在WebProject \\ Models文件夹中创建DetailsModel。 I usually create a subfolder for each controller. 我通常为每个控制器创建一个子文件夹。

WebProject\\Models\\ControllerName WebProject \\型号\\ ControllerName

public class DetailsModel
{
    public string CompanyName { get; set; }
    public string UserName { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM