I am trying to add sorting to a Razor Page by simply passing sort parameters to a class which should ideally use them properly. The problem is that the directions from Microsoft for how to implement sorting in a Razor page do not tell how to do this. The instructions at https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-6.0 come up short by telling people to hard code sorting parameters and does not provide a dynamic solution.
I want to be able to pass any sort parameter from a Razor page to a service class that will then take that parameter and plug it into the ORDER BY part of the query.
My view code is quite simple. It is like this:
string sortBy = "post.Postid";
string sortDirection = "descending";
Posts = await PostService.GetPaginatedResultSorted(CurrentPage, PageSize, sortBy, sortDirection);
My class is far more complicated, so here is a redacted version. As you can see it plugs the sortBy parameter in where I used to simply type by hand post.Postid. However, passing "post.Postid" as a string from the view does not work. I didn't expect it would, but I thought it would crash the page and produce an error message due to that string not being the same type. I don't know what type it really is, but in my experience Microsoft loves to uses types as an excuse to stop processing the query. In this case it simply returns the results unsorted.
public async Task<List<Posts>> GetPaginatedResultSorted(int currentPage, int pageSize, string sortBy, string sortDirection)
return await (from post in _context.Posts
orderby sortBy descending
select post into pts
select new Posts
REDACTED }).Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
I tried changing the orderby part to say "sortBy sortDirection" but that results in a runtime error. I would appreciate it if a Microsoft employee would be nice enough to respond by explaining why their example does not say how to dynamically sort anything and how to do so.