使用asp.net MVC2在视图中显示两个查询的结果

时间:2010-10-06 13:35:02

标签: asp.net-mvc-2

我有这个代码可行。

public class HelloWorldController : Controller
{
    UAStagingEntities db = new UAStagingEntities();

    public ActionResult Index(int? id)
    {
        var depot = db.CSLA_DEPOT.Where(c => c.DEPOT_ID == id.Value);

        return View(depot.ToList());
     }

}

我不知道该怎么做是显示包含两个查询结果的视图。如何创建视图以显示库和地址?以及如何编写return语句?

public class HelloWorldController : Controller
{
    UAStagingEntities db = new UAStagingEntities();

    public ActionResult Index(int? id)
    {
         var depot = db.CSLA_DEPOT.Where(c => c.DEPOT_ID == id.Value);
         var Address = db.CSLA_ADDRESS.Where(a => a.CSLA_DEPOT.DEPOT_ID == id.Value);

         return View(depot.ToList());
    }
}

编辑*

我添加了这个模型

    namespace CustomerCareMVC.Models
{
    public class CSLA_StagingModel

    {

        public List<CSLA_DEPOT> depots { get; set; }
        public List<CSLA_ADDRESS> addresses { get; set; }

    }

}

并在控制器中添加了此方法

    public ActionResult ShowAllTables() 
    {


        var model = new CSLA_StagingModel()
        {

            depots = db.CSLA_DEPOT.Where(c => c.DEPOT_ID == 10065),
            addresses = db.CSLA_ADDRESS.Where(a => a.CSLA_DEPOT.DEPOT_ID == 10065),
        };


        return View(model);

    }

我在这两行下面得到了波浪线

            depots = db.CSLA_DEPOT.Where(c => c.DEPOT_ID == 10065),
            addresses = db.CSLA_ADDRESS.Where(a => a.CSLA_DEPOT.DEPOT_ID == 10065),

出现此错误消息

错误1无法将类型'System.Linq.IQueryable'隐式转换为'System.Collections.Generic.List'。存在显式转换(您是否缺少演员?)C:\ CustCareMVC \ CustomerCareMVC \ CustomerCareMVC \ Controllers \ HelloWorldController.cs 59 26 CustomerCareMVC

2 个答案:

答案 0 :(得分:2)

您需要创建一个具有以下参数的ViewModel:

public IQueryable<CSLA_DEPOT> depots {get; set;}
public IQueryable<CSLA_ADDRESS> addresses {get; set;}

然后,您需要在控制器中创建这个新视图模型的实例,如下所示:

var model = new ViewModelName(){
    depots = db.CSLA_DEPOT.Where(c => c.DEPOT_ID == id.Value),
    addresses = db.CSLA_ADDRESS.Where(a => a.CSLA_DEPOT.DEPOT_ID == id.Value),
};

然后您需要将此模型传递给您的视图,如下所示:

return View(model);

在您的视图中,您将访问两个不同的集合,如下所示:

Model.depots
Model.addresses

希望这有帮助,如果您有任何问题,请给我留言。

答案 1 :(得分:0)

创建一个特殊对象,其中包含查询返回的两类类型。然后,您可以在View中使用Model.depot和Model.Address访问它们。