MVC - 传递多个数据表视图 [英] MVC - Passing multiple data tables to a view

查看:139
本文介绍了MVC - 传递多个数据表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有我的MVC项目的HomeController以下code:

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?

推荐答案

是的,有,但并不完全这样。做你想要做的事情的方法是创建一个自定义视图模型类。这个类(的 MyPageViewModel 的)将有两个(或更多)的属性,为您的每个对象。在你看来,你会使用访问它们 Model.Table1Data Model.Table2Data

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 自定义ViewModel类非常简单:

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

查看将需要强类型以这个定制ViewModel类。

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)" %>

不要试图键入youself;更容易地创建一个新的观点并勾选强类型的看法,并指定新的自定义ViewModel类。

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.

那么你的动作控制器方法是:

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

这篇关于MVC - 传递多个数据表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆