https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/razor-pages/search
本文档中,将向索引页面添加搜索功能以实现按“流派”或“名称”搜索电影。
使用以下代码更新Index页面的 OnGetAsync 方法:(注意是更新,而不是添加)
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(); }
OnGetAsync 方法的第一行创建了 LINQ 查询用于选择电影:
var movies = from m in _context.Movie select m;
此时仅对查询进行了定义,它还不会针对数据库运行。
如果 searchString 参数包含一个字符串,电影查询则会被修改为根据搜索字符串进行筛选:
if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); }
Query Execution(查询执行)。
在 SQLite 中,由于使用了默认排序规则,因此需要区分大小写。
筛选的电影将显示出来。
如果向Index页面添加了以下路由模板,搜索字符串则可作为 URL 段传递(例如 http://localhost:5000/Movies/ghost)。
@page "{searchString?}"
中的 ? 表示这是可选路由参数。
,请将它删除。
打开 Pages/Movies/Index.cshtml 文件,并添加以下代码中突出显示的 <form> 标记:
@page @model RazorPagesMovie.Pages.Movies.IndexModel @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-page="Create">Create New</a> </p> <form> <p> Title: <input type="text" name="SearchString"> <input type="submit" value="Filter" /> </p> </form> <table class="table"> @*Markup removed for brevity.*@
保存更改并测试筛选器。
按流派搜索
将以下突出显示的属性添加到 Pages/Movies/Index.cshtml.cs:
public class IndexModel : PageModel { private readonly RazorPagesMovie.Models.MovieContext _context; public IndexModel(RazorPagesMovie.Models.MovieContext context) { _context = context; } public List<Movie> Movie; public SelectList Genres;//引入命名空间 using Microsoft.AspNetCore.Mvc.Rendering; public string MovieGenre { get; set; }
这使用户能够从列表中选择一种流派。
MovieGenre 属性包含用户选择的特定流派(例如“西部”)。
使用以下代码更新 OnGetAsync 方法:
// Requires using Microsoft.AspNetCore.Mvc.Rendering; public async Task OnGetAsync(string movieGenre, string searchString) { // Use LINQ to get list of genres. 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(); }
下面的代码是一种 LINQ 查询,可从数据库中检索所有流派。
// Use LINQ to get list of genres. IQueryable<string> genreQuery = from m in _context.Movie orderby m.Genre select m.Genre;
流派的 SelectList 是通过投影截然不同的流派创建的。
Genres = new SelectList(await genreQuery.Distinct().ToListAsync());
添加“按流派搜索”
更新 Index.cshtml,如下所示:
@page @model RazorPagesMovie.Pages.Movies.IndexModel @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-page="Create">Create New</a> </p> <form> <p> <select asp-for="MovieGenre" asp-items="Model.Genres"> <option value="">All</option> </select> Title: <input type="text" name="SearchString"> <input type="submit" value="Filter" /> </p> </form> <table class="table"> <thead>
通过按流派或/和电影标题搜索来测试应用。