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

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 movies;
        public SelectList genres;
        public String movieGenre { get; set; }
    }

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

 //实现搜索功能
        // GET: Movies
        public async Task Index(String movieGenre,String searchString)
        {
            //从数据库中检索所有genre数据,并进行排序
            IQueryable 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.添加搜索按钮

Title:




你可能感兴趣的:(ASP.NET,Core)