The following tutorial is based on "Get started with Razor Pages in ASP.NET Core" from docs.microsoft.com.
-
In the Visual Studio Installer, install the following workloads:
- ASP.NET and web development
-
Tutorial 1- Create a Razor Page application
-
Tutorial 2- Add a Model
-
Tutorial 3- Update Page
In this tutorial, you're going to search to the Index Page. By the end of this tutorial, you'll be able to search by genre and name.
Open Pages/Movies/Index.cshtml.cs
and replace the OnGetAsync
method with the following code:
public async Task OnGetAsync(string searchString)
{
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
Movie = await movies.ToListAsync();
}
- Run your application with F5 and open the Movies Page (
http://localhost:{port}/Movies
). - Append the query string to the end
?searchString=[Film Title]
(for example,http://localhost:{port}/Movies?searchString=panther
)
-
Open the
Pages/Movies/Index.cshtml
file and add the<form>
element as shown in the following code:<h1>Index</h1> <p> <a asp-page="Create">Create New</a> </p> <form> <p> Movie Title: <input type="text" name="SearchString"> <input type="submit" value="Filter"/> </p> </form>
-
Run the application with F5 and open the Movies Page (
http://localhost:{port}/Movies
). -
Enter a film title in the search box.
-
Open the
Pages/Movies/Index.cshtml.cs
file and add the following code:public class IndexModel : PageModel { private readonly RazorPagesMovie.Data.RazorPagesMovieContext _context; public IndexModel(RazorPagesMovie.Data.RazorPagesMovieContext context) { _context = context; } public IList<Movie> Movie { get;set; } = default!; public SelectList Genres; public string MovieGenre { get; set; }
-
Update the
OnGetAsync
method on that same file:public async Task OnGetAsync(string movieGenre,string searchString) { IQueryable<string> genreQuery = from m in _context.Movie orderby m.Genre select m.Genre; var movies = from m in _context.Movie select m; if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); } if (!String.IsNullOrEmpty(movieGenre)) { movies = movies.Where(x => x.Genre == movieGenre); } Genres = new SelectList(await genreQuery.Distinct().ToListAsync()); Movie = await movies.ToListAsync(); }
-
Open the
Pages/Movies/Index.cshtml
file and update the form element code:<form> <p> <select asp-for="MovieGenre" asp-items="Model.Genres"> <option value="">All</option> </select> Movie Title: <input type="text" name="SearchString"> <input type="submit" value="Filter"/> </p> </form>
-
Run the application with F5 and open the Movies Page (
http://localhost:{port}/Movies
). -
Enter a film genre in the drop down control.
Mission accomplished!
Congratulations! You've built your first Razor Page application.