简体   繁体   中英

How to display data from multiple tables in view in asp.net MVC

I have three tables called Material Group, Material Class, Material Type. There is parent child relation between Group and Class as well as Class and Type but there is no direct relation in between Group and Type table.

Below is controller's current code:

var ctbl_MaterialType = db.ctbl_MaterialType.Include(c => c.ctbl_MaterialClass).Include(c => c.stbl_Supplier).ToList();

return View(ctbl_MaterialType);

I'm not able to include Group table as there is no direct relationship. Even I tried below code but gave me error:

var ctbl_MaterialType = ( from mt in db.ctbl_MaterialType join mc in db.ctbl_MaterialClass on mt.ID_ctbl_MaterialClass equals mc.ID_ctbl_MaterialClass
where mt.ID_ctbl_MaterialClass == mc.ID_ctbl_MaterialClass
join mg in db.ctbl_MaterialGroup on mc.ID_ctbl_MaterialGroup equals mg.ID_ctbl_MaterialGroup
where mc.ID_ctbl_MaterialGroup == mg.ID_ctbl_MaterialGroup
join ms in db.stbl_Supplier on mt.ID_stbl_Supplier equals ms.ID_stbl_Supplier
where mt.ID_stbl_Supplier == ms.ID_stbl_Supplier select new {
                                          MaterialGroup = mg.MaterialGroup,
                                          MaterialClass = mc.MaterialClass,
                                          MaterialType = mt.MaterialType,
                                          MaterialTypeAlias= mt.MaterialTypeAlias,
                                          Supplier = ms.Supplier
                                      });
return View(ctbl_MaterialType);

How can I include group table so that I can use it in view for display??

Create a ViewModel. ViewModel is a class that wraps all your other models that you need to send to your view.

Example: I'll create a view model that holds the list of students and the list of cities.

View model class:

public class HomeIndexVM //(controllerName + actionName + VM)
{
    public List<Student> Students { get; set; }
    public List<City> Cities { get; set; }
}

In your action:

HomeIndexVM viewModel = new HomeIndexVM {
    Students = context.Students.ToList();
    Cities = context.Cities.ToList();
};

return View(viewModel);

In your view:

@model HomeIndexVM

foreach(Student student in Model.Students) {
    //...
}

I hope you'll get the point. Happy coding.

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