The following tutorial is based on "Get started with Razor Pages in ASP.NET Core" from docs.microsoft.com.
- Visual Studio 2022 for Mac Preview
- In the Visual Studio for Mac Installer, install the .NET Core target.
- Tutorial 1- Create a Razor Page application
- Tutorial 2- Add a Model
- Tutorial 3- Update Page
In this tutorial, you're going to add 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 by selecting Debug > Run without Debugging on the main menu.
-
If you haven't created a few movies, go ahead and do that now.
-
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 by selecting Debug > Run without Debugging on the main menu.
-
Navigate to
https://localhost:{port}/Movies
Mission accomplished!
You've built your first Razor Page application with C# and ASP.NET Core.