Search code examples
c#asp.net-mvclinqasp.net-mvc-viewmodel

MVC - Passing multiple data tables to a view


I currently have the following code in the HomeController of my MVC project:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        MyDataContext dc = new MyDataContext();

        IQueryable<Table1Data> j =
            from n in dc.Table1                     
            select n;

        return View(j);
    }

So that works okay, but now I want to pass a second table through to the same view. So I was thinking I should be able to do something like this:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        MyDataContext dc = new MyDataContext();

        IQueryable<Table1Data> j =
            from n in dc.Table1                     
            select n;

        IQueryable<Table2Data> l =
            from k in dc.Table2        
            select k;

        return View(j, l);
    }

Is there a way to have the view accept two models like this or, alternatively, a way to merge the two result sets (the two tables are not linked in any way?


Solution

  • Yes there is, but not quite like that. The way to do what you wish to do is to create a custom ViewModel class. This class (MyPageViewModel) would have two (or more) properties, one for each of your objects. In your view, you would access them using Model.Table1Data and Model.Table2Data.

    A custom ViewModel class is very simple:

    public class MyPageViewModel
    {
       public IQueryable<Table1Data> Table1Data { get; set; }
       public IQueryable<Table2Data> Table2Data { get; set; }
    }
    

    You view would need to be strongly typed to this custom ViewModel class.

    <%@ Page Title="MyPage" MasterPageFile="~/Application/Master Pages/Site.Master"
        Inherits="System.Web.Mvc.ViewPage(Of MyAppNamespace.MyPageViewModel)" %>
    

    Don't try to type that youself; easier to create a new view and check "strongly typed" view, and specify your New Custom Viewmodel class.

    Then your action Controller method would be:

    public class HomeController : Controller
    {
      public ActionResult Index()
      {
        MyDataContext dc = new MyDataContext();
    
        MyPageViewModel vm = new MyPageViewModel();
    
        vm.Table1Data =  from n in dc.Table1                     
                         select n;
    
        vm.Table1Data = from k in dc.Table2        
                        select k;
    
        return View(vm);
      }
    }