ASP.NET MVC "search" should redirect to result or results

I have a search action that accepts a search parameter. I have search results in one result, and I want to redirect the show action, and if there are several results, I want to direct a list action with all the results listed.

I got a redirect to work, but not quite good. I am not sure how to do the transfer of search results. Should the first β€œsearch” action retrieve only the identifier and then perform the show or list action to retrieve more data based on id? How should their identifier be transferred to a specific action?

+4
source share
2 answers

I would probably have a search action that displays a result with search results if there are multiple results. It could reuse the list view if necessary, but it would be easier to just display them, rather than trying to redirect to another action with multiple identifiers. In the case of a single result, redirection to the action of information for this element may be required. This would mean that I would need to get enough data during the search to populate the model for the list. If you are redirected to an action with details, you simply redirect by id and allow the action of the part to receive any information necessary to display it.

public ViewResult Search( string query ) { ... get results .. if (results.Count() == 1) { return RedirectToAction( "details", new { id = results.First().ID } ); } return View( "list", this.CreateListViewModel( results ) ); } 

where CreateListViewModel takes a set of search results and creates a view model object to represent the list.

+2
source

Another possibility for this is to create two views: one for one result and one for the list result and call return View("Single", model) or View("List, collection) .

0
source

Source: https://habr.com/ru/post/1345455/


All Articles