MVC: Search Page

Creating a Search Page

Create a View for the Search

Create a view at Views/Home/Search.cshtml and add some basic HTML.

VIEW: Views/Home/Search.cshtml

This adds a HTML form with an asp-action of Search. At run time this Tag Helper will add the Search controller as the action of the form.

The form will also be given a method of post. This means the SearchString will be 'posted' back to the controller.

Set Up the Controller

Amend the Controller/HomeController.cs by adding an action called Search.

CONTROLLER: Controllers/HomeController.cs

This Action performs a number tasks that needs some explanation.

Firstly, the Action receives String parameter of SearchString as we saw declared in the form.

Next, a query is build using LINQ to query the Films table in the database, extracting all the data into the variable films. This is done when the page is first called thus all films are by default display (we'll fix this later).

A condition checks to see if SearchString is null or empty. If not then a LINQ Contains query is build with the SearchSring as it contains value.

In each scenario the data is run through the ToList() method to create a list of films for trhe model.

The model is passed to the View but before that is returned, ViewData is used to also return the SearchString to the view if required.

Amending the View to Display the Data

Add a foreach loop to display the data.

VIEW: Views/Home/Search.cshtml

Tidy Up the Output

When first viewing the page all the data is listed and we also have no user response is no data is found. Amend the output code the some conditional logic as follows:

VIEW: Views/Home/Search.cshtml

Amending the View to Pass the Id to the Details Page

Amend the Views/Home/Search.cshtml View to link to the FilmDetails passing the id of the film.

This is done by using the Tag Helper asp-controller, asp-action and asp-route-id

VIEW: Views/Home/Search.cshtml

Save and test via the localhost:5001/Home/Search to link to the FilmDetails.

Notice the URL appears as localhost:5001/Home/FilmDetails/2

Make the Search Bookmarkable

With a form of method post the results page is not bookmarkable as the SearchString parameter is in the request body and not the URL/querystring.

This can be fixed by changing the form method on the view to getie:

VIEW: Views/Home/Search.cshtml

Searches can now be booked for example as https://localhost:5001/Home/Search?SearchString=star%20wars