【ASP.NET Core 2.0】一覧ページに検索機能を追加する
以下の記事の続きです。
公式のチュートリアルに沿って行います。
一覧ページに検索機能を追加します。
任意のタイトルで検索できるよう、検索フォームの追加と Get メソッドの編集を行います。
OnGetAsync メソッドを以下のように編集します。
\Pages\Movies\Index.cshtml.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using RazorPagesMovie.Models; namespace RazorPagesMovie.Pages.Movies { public class IndexModel : PageModel { private readonly MovieContext _context; public IndexModel(MovieContext context) => this._context = context; public IList<Movie> Movies { get; set; } public async Task OnGetAsync(string title) { IQueryable<Movie> movies = from m in this._context.Movie select m; if (!string.IsNullOrWhiteSpace(title)) { movies = movies.Where(m => m.Title.Contains(title)); } this.Movies = await movies.ToListAsync(); } } }
LINQ は遅延実行のため ToList されるまで実行されません。
もし、引数のタイトルが空文字やスペースでない場合、クエリに条件を足しています。
(※チュートリアルでは IsNullOrEmpty ですが IsNullOrWhiteSpaceとしました。)
OnGetAsync が正しく動作するか確認します。
アプリを起動し、アドレスバーに以下のように入力します。
http://localhost:アプリのポート番号/Movies?title=Ghost
タイトルに "Ghost" を含む映画の一覧が表示されました。
検索フォームを追加します。
\Pages\Movies\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> @Html.DisplayNameFor(model => model.Movies[0].Title) : <input type="text" name="title" /> <input type="submit" value="検索" /> </p> </form> <table class="table"> <-- 以下略 -->
検索が正常に行われました。