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>
本文介绍了如何在ASP.NET Core应用中实现搜索功能。通过建立Movie类,创建电影分类,然后在控制器的Index方法中添加searchString参数,并利用LINQ查询来搜索Movie数据。
2381

被折叠的 条评论
为什么被折叠?



