Razor Pages (an alternative to MVC)

Menu
Menu

Razor Pages Search and Results

Setting Up a Page and PageModel

In the pages create a new Razor Page called AllFilms.cshtml as previously described ensuring a PageModel is created as well.

This will create a .cshtml Page and an associated .cshtml.cs PageModel file.

Set Up the PageModel File to Retrieve the Data

Add a new private readonly variable for the database context.

PAGEMODEL: Pages/SearchPage.cshtml.cs

Create a constructor that uses dependency injection to reference the database context. This removes the need to manage a database context object in this file.

PAGEMODEL: Pages/SearchPage.cshtml.cs

Create a List named FoundFilms to hold the film found by the search.

PAGEMODEL: Pages/SearchPage.cshtml.cs

Create a string variable called SearchString. This contains the text users enter in the search text box. SearchString has the [BindProperty] attribute. [BindProperty] binds form values and query strings with the same name as the property. The parameter of (SupportsGet = true) is required for binding on GET requests.

PAGE MODEL: Pages/SearchPage.cshtml.cs

Use a LINQ Method Syntax to search the Films table with a Contains().

Tip: Use the CTRL . to add the required dependencies in this case EntityFrameWorkCore.

Amend the onGet() handler as follows:

PAGEMODEL: Pages/SearchPage.cshtml.cs

Add a Search Form to the Page File

Build a simple HTML form with an input tag helper of asp-for on the input element.

PAGE: Pages/SearchPage.cshtml

Amending the Page File to Display the Data

Add a foreach loop to display the data.

PAGE: Pages/SearchPage.cshtml

Tidy Up the Output

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

PAGE: Pages/SearchPage.cshtml