如何使用ASP.NET Core实现搜索功能

    xiaoxiao2021-03-25  138

    1.建立Movie类

    public class Movie { public int ID { get; set; } public String Title { get; set; } [Display(Name = "Release Date"), DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode =true)] public DateTime ReleaseDate { get; set; } public decimal Price { get; set; } public String Genre { get; set; } } 2.创建控制器

    3.创建电影分类类别

    public class MovieGenreViewModel { public List<Movie> movies; public SelectList genres; public String movieGenre { get; set; } }

    4.在控制器Index方法中添加searchString参数,并使用linq搜索到所有Movie数据

    //实现搜索功能 // GET: Movies public async Task<IActionResult> Index(String movieGenre,String searchString) { //从数据库中检索所有genre数据,并进行排序 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); } var movieGenreVM = new MovieGenreViewModel(); movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync()); movieGenreVM.movies = await movies.ToListAsync(); return View(movieGenreVM); }5.添加搜索按钮

    <form asp-controller="Movies" asp-action="Index" method="get"> <select asp-for="movieGenre" asp-items="Model.genres"> <option value="">ALL</option> </select> <p> Title:<input type="text" name="SearchString" /> <input type="submit" value="search" /> </p> </form>

    转载请注明原文地址: https://ju.6miu.com/read-3179.html

    最新回复(0)