Kevin M.
Kevin M.

Reputation: 21

Get next / previous record in ASP.NET Core MVC using Dapper

I'm pulling list data into a grid, and viewing them one-by-one in a "detail view". I'm trying to add a Next/Previous button that will allow me to easily navigate between the details of each item from my list.

Here is the code I'm using within my controller

var nextID = _movieRepository.GetAll()
                             .OrderBy(i => i.movie_id)
                             .SkipWhile(i => i.movie_id != i.movie_id)
                             .Skip(1)
                             .Select(i => i.movie_id);

ViewBag.NextID = nextID;

Within my breakpoint, it is only returning "nextID = NULL" which means it does not generate the appropriate next Record ID at the end of my URL. Note: I am using the Linq namespace in my controller, but I'm not using EF. This is the simple code I have in my view.

<a href="/@ViewData["Controller"]/@ViewData["Action"]/@ViewBag.nextID"> Next Movie </a>

I've been Googling, trying different methods, different combination of the Skip/SkipWhile/Select/FirstOrDefault, and nothing has worked. Any assistance or insight on this is much appreciated.

Upvotes: 1

Views: 692

Answers (1)

Serge
Serge

Reputation: 43959

you have a bug in your code

  .SkipWhile(i => i.movie_id != i.movie_id)

is always false, so you will always have all records minus one, instead of one record.

I assume that you have movie_id and you need the next larger id after this , so try this code

var nextID = _movieRepository.GetAll()
                             .OrderBy(i => i.movie_id)
                             .Where(i => i.movie_id > movie_Id )
                             .Select(i => i.movie_id)
                             .FirstOrDefault();

this query will return next movie_id after current movie_id

Upvotes: 2

Related Questions