The tutorial below is based on "Get started with Razor Pages in ASP.NET Core" from docs.microsoft.com.
- Visual Studio 2017
- In the Visual Studio Installer, install the following workloads:
- ASP.NET and web development
- .NET Core cross-platform development
- Tutorial 2- Add a Model
- Tutorial 3- Update Page
In this quick tutorial we are going to search to the Index Page. By the end of this tutorial you can search by genre and name.
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 again with F5 and navigate back to the Movies Page
- Append the query string to the end
?searchString=[Film Title]
(for example:http://localhost:5000/Movies?searchString=Wrinkle
)
Search by Title
<h2>Index</h2>
<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
http://localhost:5000/movies
- Enter a film title
Search by Genre
Note: you will need to add using Microsoft.AspNetCore.Mvc.Rendering;
public class IndexModel : PageModel
{
private readonly RazorPagesMovie.Models.MovieContext _context;
public IndexModel(RazorPagesMovie.Models.MovieContext context)
{
_context = context;
}
public IList<Movie> Movie;
public SelectList Genres;
public string MovieGenre { get; set; }
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();
}
<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
Mission Accomplished
You've have built your first Razor Page application