Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should navigation logic be in the controller or the view?

In an MVC web app, where is the "right" place to put the code/logic to display a url link to a "next page" navigation control, the controller or the view? If I put it in the view, I have to pass to the view not only the data to be displayed on the current page but also data relating to the next page aka the page id of the next page. If I put it in the controller, the controller has to be aware of the navigation that the particular view is going to display. Neither approach seems very elegant to me. Is there another way?

like image 593
Charlotte Moller Avatar asked Nov 06 '22 19:11

Charlotte Moller


1 Answers

I don't know if there really is a "right" way to do this. Here's some different ways that I would think about it though:

  • if a page of items is itself an object in the system, then the controller makes sense
  • if a page only exists within the view logic, then the view makes sense
  • if the view receives the entire list, then pagination is a presentation concept
  • if you foresee the need for different page sizes or organizations, then keep the logic out of the controller

My gut says that you should try very hard to keep all of the pagination logic in the view. This usually means that you want some way to calculate what the next page is based on the current page in the view or make the controller have some concept of a starting point in the result set. I usually do the latter - the view retrieves the data with an optional starting point that is the ID of the last item on the previous page. This way the pagination logic is in the view and the data retrieval is simple.

One of the things to watch out for is how you will handle retrieving the next page of data if the item that you are keying on no longer exists. In other words, if you link says "the first page following item A" and "item A" has been deleted, then you need to do something reasonable.

like image 112
D.Shawley Avatar answered Nov 29 '22 16:11

D.Shawley