NealR
NealR

Reputation: 10669

Unable to add to IPagedList object or transfer List<T> to IPagedList<T>

I'm using the Page List ASP MVC plugin to add paging to my View as my view model contains a list that gets a little out of control at time. However, I'm running into a few issues.

View Model

public IPagedList<ZipCodeTerritory> zipCodeTerritory { get; set; }

Controller

search.zipCodeTerritory = (from z in db.ZipCodeTerritory
                          where z.StateCode.Equals(search.searchState) &&
                                z.EffectiveDate >= effectiveDate
                         select z).ToList().ToPagedList(pageNumber, pageSize);

//This works but this only covers one of the three different searches that are 
//possibly from this Index page

View Model

public IPagedList<ZipCodeTerritory> zipCodeTerritory { get; set; }

Controller

foreach (var zip in zipArray)
{
    var item = from   z in db.ZipCodeTerritory
                where  z.ZipCode.Equals(zip) &&
                        z.EffectiveDate >= effectiveDate &&
                        z.IndDistrnId.Equals(search.searchTerritory) &&
                        z.StateCode.Equals(search.searchState)
                select z;
    search.zipCodeTerritory.AddRange(item); //This line throws the following exception:

    //PagedList.IPagedList<Monet.Models.ZipCodeTerritory>' does not contain a 
    //definition for 'AddRange' and no extension method 'AddRange' accepting a first 
    //argument of type 'PagedList.IPagedList<Monet.Models.ZipCodeTerritory>' could be 
    //found (are you missing a using directive or an assembly reference?)
} 

View Model

    public IPagedList<ZipCodeTerritory> pagedTerritoryList { get; set; }
    public List<ZipCodeTerritory> zipCodeTerritory { get; set; }

Controller

search.pagedTerritoryList = (IPagedList<ZipCodeTerritory>)search.zipCodeTerritory;

//This threw the following exception at runtime: 
//Unable to cast object of type  
//System.Collections.Generic.List'1[Monet.Models.ZipCodeTerritory]' to type 
//'PagedList.IPagedList'1[Monet.Models.ZipCodeTerritory]'.

Upvotes: 2

Views: 13668

Answers (1)

GalacticCowboy
GalacticCowboy

Reputation: 11759

To combine your various approaches together, you probably should do something like this (based on your first example):

var mySearch = (from z in db.ZipCodeTerritory
                      where z.StateCode.Equals(search.searchState) &&
                            z.EffectiveDate >= effectiveDate
                     select z);

// Other searches, whatever; use mySearch.AddRange() here

search.zipCodeTerritory = mySearch.ToPagedList(pageNumber, pageSize);

Upvotes: 5

Related Questions