我如何将PagedList应用于viewModel类而不是Model类

时间:2013-08-09 14:17:27

标签: asp.net-mvc linq entity-framework

我正在使用两个连接到两个不同数据库的上下文类。但是在我的索引视图中,我需要从两个数据库中获取信息,然后将分页应用于连接结果。为此,我定义了以下viewModel类: -

public class RackJoinList
{
  public IEnumerable<TMSRack> Racks { get; set; } // from the first database
  public IEnumerable<Resource> Resources { get; set; } //from the second database
}

以下用于填充ViewMaodel对象的存储库方法: -

 public RackJoinList AllFindRacks_j(string q,bool forautocomplete=false)
 {
   RackJoinList rjlist = new RackJoinList();
   var racks = from rack in tms.TMSRacks.Where(
                a => a.Technology.Tag.ToUpper()
                  .StartsWith(q.ToUpper()) || (q == null)
               )
               select rack;

    rjlist.Racks = racks.ToList();
    var resources = from resource in entities.Resources
                    join c in rjlist.Racks
                    on resource.RESOURCEID equals c.Technology.IT360ID
                    select resource;
    rjlist.Resources = resources;
    return rjlist;
 }

最后我有以下Action方法: -

 public ActionResult Index(string searchTerm=null, int page = 1)
 {
   var racks = repository.AllFindRacks_j(searchTerm)
                 .OrderBy(a=>a.Technology.Tag).ToPagedList(page, 5) ;

   return View(racks);
 }

但是上面的操作方法会引发错误,因为我无法将order by和Ipagedlist应用于非list对象。所以任何人都可以就如何解决我的问题提出建议,主要是: -

  1. 加入来自不同数据库的上下文类。

  2. 将分页应用于联接结果。

  3. 感谢adbacne的任何帮助。

1 个答案:

答案 0 :(得分:0)

所以,你有:

public class RackJoinList
{
  public IEnumerable<TMSRack> Racks { get; set; } // from the first database
  public IEnumerable<Resource> Resources { get; set; } //from the second database
}

再添加一个ViewModel:

public class Pagedclass
{
public IPagedList<RackJoinList> mylist {get; set;}
}

在你的ActionResult中:

public ActionResult Index(string searchTerm=null, int page = 1)
 {
   var racks = repository.AllFindRacks_j(searchTerm)
                 .OrderBy(a=>a.Technology.Tag).ToPagedList(page, 5) ;

var model = new Pagedclass
{
mylist = racks
};

   return View(model);
 }

您的视图应该从Pagedclass:@model YourProject.ViewModels.Pagedclass

进行严格输入

编辑:

public ActionResult Index(string searchTerm=null, int page = 1)
     {
       var racks = repository.AllFindRacks_j(searchTerm);

      var _racks = racks.OrderBy(a=>a.Technology.Tag).ToPagedList(page, 5)

    var model = new Pagedclass
    {
    mylist = _racks
    };

       return View(model);
     }