ASP.NET Core: Razor Pages

Creating a Search Page

Setting Up a Page and Page Model

In the pages/Films folder, create a page called SearchPage.cshtml. Do so via:

This will create a .cshtml page and an associated .cshtml.cs page model file.

Set Up the Page Model File to Retrieve the Data

Add a new private readonly variable for the database context.

PAGE MODEL: Pages/Films/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.

Tip: Use the snippet ctor TAB TAB to build a constructor shell.

PAGE MODEL: Pages/Films/SearchPage.cshtml.cs

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

PAGE MODEL: Pages/Films/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/Films/SearchPage.cshtml.cs

Use LINQ's Where(Contains()) to search the table.

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

Amend the onGet() handler as follows:

PAGE MODEL: Pages/Films/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/Films/SearchPage.cshtml

Amending the Page File to Display the Data

Add a foreach loop to display the data.

PAGE: Pages/Films/SearchPage.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:

PAGE: Pages/Films/SearchPage.cshtml