简体   繁体   中英

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. From my understanding, I would need to create a class in Model. In the Controller, I would then call that class. 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?

Are you planning to use SQL Server and Entity Framework or what?

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.

Most of us are using a ORM like nhibernate or entity framework to handle data access. 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. I usually create a subfolder for each controller.

WebProject\\Models\\ControllerName

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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