Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...