In Asp.Net 4.8 web app, the following works. I’m using PagedList for pagination.
private AppDbContext db = new AppDbContext();
private IQueryable<Border> Broders;
public ViewResult Index(int? page)
{
Broders = from s in db.Broders select s;
if (SearchColumn == "T1")
{
Borders = Broders.Where(s => s.TagT1.ToString().Contains(searchString));
}
else if (SearchColumn == "T2")
{
Borders = Broders.Where(s => s.TagT2.ToString().Contains(searchString));
}
switch (sortOrder)
{
case "status_desc":
Borders = Borders.OrderByDescending(s => s.Status);
break;
case "status_desc":
Borders = Borders.OrderByDescending(s => s.Status);
break;
default:
Borders = Borders.OrderByDescending(s => s.CreatedOn);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(Borders.ToPagedList(pageNumber, pageSize));
}
But when I do this in .Net 8 Asp.Net MVC Core app, I’m using X.PagedList for pagination.
private readonly AppDbContext _context;
private IQueryable<Broder> Borders;
public async Task<IActionResult> Index(int? page)
{
var Borders = await _context.Borders.ToListAsync();
if (SearchColumn == "T1")
{
Borders = (List<Initiative>)Broders.Where(s => s.TagT1.ToString().Contains(searchString));
}
else if (SearchColumn == "T2")
{
Borders = (List<Initiative>)Broders.Where(s => s.TagT2.ToString().Contains(searchString));
}
switch (sortOrder)
{
case "status_desc":
Borders = (List<Initiative>)Borders.OrderByDescending(s => s.Status);
break;
case "status_desc":
Borders = (List<Initiative>)Borders.OrderByDescending(s => s.Status);
break;
default:
Borders = (List<Initiative>)Borders.OrderByDescending(s => s.CreatedOn);
break;
}
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(Borders.ToPagedList(pageNumber, pageSize));
}
The above asp.net Core code gives me error InvalidCastException: Unable to cast object of type ‘System.Linq.OrderedEnumerable2[Map.Models.Border,System.String]' to type 'System.Collections.Generic.List
1[Map.Models.Border]’ at line
Borders = (List<Initiative>)Borders.OrderByDescending(s => s.CreatedOn);
I’m new to asp.net Core, this is my first application in asp.net core. Can someone tell me what mistake am I making in my asp.net core method?
2
Answers
In your second code block you use
var Borders = ...
whcih defines a new variable of a different type (implied from the return ofToList
and hides the page field. So just removing thevar
would be a start to get them in sync, but it may require other changes as well.For example, you may also need to remove the
ToList
since a list cannot be assigned to anIQueryable
variable. It will also stop loading the entireBorders
table in memory only to apply filters after that.From this line:
you are declaring
Borders
which is aList<Border>
type.Changes:
Declare the
Borders
asIQueryable<Border>
with.AsQueryable()
.Remove casting to
List<Initiative>
which seems unnecessary.Don’t need to create variable with global scope:
private IQueryable<Broder> Borders;