MVC: Search Page

Menu
Menu

Creating a Search Page

We have listed individual films and mulitiple films based on hard-corded queries. However, for our application to be useful we'd want users to be able to search the Films table. Here we'll build a search page allowing using to search the Films table by FilmTitle.

Supporting Video: Building a Details and a Search and Results 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

Ordinarily the Tag Helper asp-action would add a method of post. However, as we'll want to use get to send the data, we've added the method attribute with a value of get. (Using get and a Query String will make the query bookmarkable.)

Set Up the Controller

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

CONTROLLER: Controllers/HomeController.cs

As the Form has an method of get this Action receives a String parameter of SearchString as a Query String

A condition checks to see if SearchString is null or empty.

If there is a SearchString value, a LINQ Where Contains query is built with the SearchSring as it value.

The results of the LINQ query are run through the ToList() method to create a List of films.

The model is passed to the View along with a ViewData value returning the SearchString to the view.

If SearchString is null (which is the case when the View first loads) then a View is returned with no model.

Amending the View to Display the Data

We can now amend the View with a foreach loop to display the data below the <form>.

VIEW: Views/Home/Search.cshtml

The above will produce an error as there is no Model passed to the initial View. We can use conditional logic to avoid this situation by checking for a value for ViewData["SearchString"]. We can also add a nested if using Model.count to improve the user experience in the case of the search returning no data. Amend the output code with 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

Bookmarkable Query String Search

As the search uses a Query String notice that is it bookmarkable for example as https://localhost:5001/Home/Search?SearchString=star%20wars

If the <form> had a method of post this would not have been possible.

Challenge: Can you extend the search so that it also searches by FilmCertificate value?

Can you present the film certificate values in the View as a drop-down select / option list AND have this list generated by the Controller?