MVC5学习系列——排序、过滤、分页

MVC5学习笔记,这次练习一下MVC列表的排序、筛选、分页。参考官网地址:Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application。

这次我们从头开始,首先我们创建一个空的MVC应用程序,之后先做一下准备工作,我们在根目录下添加Content文件夹并在创建子文件夹Bootstrap/3.3.6用来存放样式文件,然后Views文件夹中创建Shared/_LayoutMovie.cshtml布局文件,代码如下:





    
    @ViewBag.Title - 我的电影
    


    
@RenderBody()
随后,添加模型—Movie,代码如下:

using System;
using System.ComponentModel.DataAnnotations;

namespace DDZ.MVC5Paging.Models
{
    public class Movie
    {
        public int ID { get; set; }
        [Display(Name = "电影名称")]
        [Required]
        [MinLength(3)]
        [MaxLength(50)]
        public string Title { get; set; }
        [Display(Name = "发行日期")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime ReleaseDate { get; set; }
        [Display(Name = "电影类型")]
        [StringLength(50)]
        public string Genre { get; set; }
        [Display(Name = "电影售价")]
        [Range(0, 100)]
        public decimal Price { get; set; }
    }
}
然后,我们选中“包含视图的MVC控制器(使用Entity Framework)”,按照下图创建控制器:

MVC5学习系列——排序、过滤、分页_第1张图片

在调试之前呢,首先修改一下默认路由和web.config,如下图:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

    
   
  

 
  在配置完这些之后,我们开始调试。因为是第一次调试,程序会自动创建数据库,然后我们先插入一些数据,如下图: 
  

MVC5学习系列——排序、过滤、分页_第2张图片

重点正式开始:首先是排序,看一下视图页面代码

 
        
            @Html.ActionLink("电影名称", "Index", new { sortOrder = ViewBag.TitleSortParm})
        
        
            @Html.ActionLink("发布日期", "Index", new { sortOrder = ViewBag.ReleaseDateSortParm})
        
        
            @Html.ActionLink("体裁", "Index", new { sortOrder = ViewBag.GenreSortParm})
        
        
            @Html.ActionLink("票价", "Index", new { sortOrder = ViewBag.PriceSortParm })
        
        
    
接着是Movies控制器Index方法:

public ActionResult Index(string sortOrder)
        {
            ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewBag.ReleaseDateSortParm = sortOrder == "date" ? "date_desc" : "date";
            ViewBag.GenreSortParm = sortOrder == "genre" ? "genre_desc" : "genre";
            ViewBag.PriceSortParm = sortOrder == "price" ? "price_desc" : "price";
            var movies = from s in db.Movies
                         select s;
            switch (sortOrder)
            {
                case "title_desc":
                    movies = movies.OrderByDescending(s => s.Title);
                    break;
                case "date":
                    movies = movies.OrderBy(s => s.ReleaseDate);
                    break;
                case "date_desc":
                    movies = movies.OrderByDescending(s => s.ReleaseDate);
                    break;
                case "genre":
                    movies = movies.OrderBy(s => s.Genre);
                    break;
                case "genre_desc":
                    movies = movies.OrderByDescending(s => s.Genre);
                    break;
                case "price":
                    movies = movies.OrderBy(s => s.Price);
                    break;
                case "price_desc":
                    movies = movies.OrderByDescending(s => s.Price);
                    break;
                default:
                    movies = movies.OrderBy(s => s.Title);
                    break;
            }
            return View(movies.ToList());
        }
结果如下图:

MVC5学习系列——排序、过滤、分页_第3张图片

其次是过滤搜索,先看一下修改的视图代码:

@Html.ActionLink("添加电影", "Create")

@using (Html.BeginForm("Index", "Movies", FormMethod.Get, new { @class = "form-inline" })) {

电影名称: @Html.TextBox("searchMovieTitle", null, new { @class = "form-control", @placeholder = "请输入电影名称" }) 体裁: @Html.DropDownList("searchMovieGenre", ViewData["searchMovieGenreList"] as SelectList, "请选择体裁", new { @class = "form-control" })

}
再看一下,后台代码:

public ActionResult Index(string sortOrder, string searchMovieTitle, string searchMovieGenre)
        {
            //搜索
            ViewData["searchMovieTitle"] = searchMovieTitle;
            ViewData["searchMovieGenre"] = searchMovieGenre;

            var movies = from s in db.Movies
                         select s;
            //绑定下拉框
            var GenreQry = from d in movies
                           select d.Genre;
            ViewData["searchMovieGenreList"] = new SelectList(GenreQry.Distinct());
            //搜索
            if (!String.IsNullOrEmpty(searchMovieTitle))
            {
                movies = movies.Where(s => s.Title.Contains(searchMovieTitle));
            }
            if (!string.IsNullOrEmpty(searchMovieGenre))
            {
                movies = movies.Where(x => x.Genre == searchMovieGenre);
            }
            //排序
            ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewBag.ReleaseDateSortParm = sortOrder == "date" ? "date_desc" : "date";
            ViewBag.GenreSortParm = sortOrder == "genre" ? "genre_desc" : "genre";
            ViewBag.PriceSortParm = sortOrder == "price" ? "price_desc" : "price";
            switch (sortOrder)
            {
                case "title_desc":
                    movies = movies.OrderByDescending(s => s.Title);
                    break;
                case "date":
                    movies = movies.OrderBy(s => s.ReleaseDate);
                    break;
                case "date_desc":
                    movies = movies.OrderByDescending(s => s.ReleaseDate);
                    break;
                case "genre":
                    movies = movies.OrderBy(s => s.Genre);
                    break;
                case "genre_desc":
                    movies = movies.OrderByDescending(s => s.Genre);
                    break;
                case "price":
                    movies = movies.OrderBy(s => s.Price);
                    break;
                case "price_desc":
                    movies = movies.OrderByDescending(s => s.Price);
                    break;
                default:
                    movies = movies.OrderBy(s => s.Title);
                    break;
            }
            return View(movies.ToList());
        }
MVC5学习系列——排序、过滤、分页_第4张图片

最后是分页,首先在“程序包管理控制台” 安装 PagedList.Mvc——Install-Package PagedList.Mvc

MVC5学习系列——排序、过滤、分页_第5张图片

安装成功之后,先看一下视图页面修改的代码:
@*@model IEnumerable*@
@model PagedList.IPagedList
@using PagedList.Mvc;
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, pageNum => Url.Action("Index", new { pageNum, searchMovieTitle = ViewData["searchMovieTitle"], searchMovieGenre = ViewData["searchMovieGenre"], sortOrder = ViewBag.CurrentSort }))
然后再看一下,后台代码:
 public ActionResult Index(string sortOrder, string searchMovieTitle, string searchMovieGenre, int? pageNum)
        {
            //分页
            ViewBag.CurrentSort = sortOrder;
            //搜索
            ViewData["searchMovieTitle"] = searchMovieTitle;
            ViewData["searchMovieGenre"] = searchMovieGenre;

            var movies = from s in db.Movies
                         select s;
            //绑定下拉框
            var GenreQry = from d in movies
                           select d.Genre;
            ViewData["searchMovieGenreList"] = new SelectList(GenreQry.Distinct());
            //搜索
            if (!String.IsNullOrEmpty(searchMovieTitle))
            {
                movies = movies.Where(s => s.Title.Contains(searchMovieTitle));
            }
            if (!string.IsNullOrEmpty(searchMovieGenre))
            {
                movies = movies.Where(x => x.Genre == searchMovieGenre);
            }
            //排序
            ViewBag.TitleSortParm = String.IsNullOrEmpty(sortOrder) ? "title_desc" : "";
            ViewBag.ReleaseDateSortParm = sortOrder == "date" ? "date_desc" : "date";
            ViewBag.GenreSortParm = sortOrder == "genre" ? "genre_desc" : "genre";
            ViewBag.PriceSortParm = sortOrder == "price" ? "price_desc" : "price";
            switch (sortOrder)
            {
                case "title_desc":
                    movies = movies.OrderByDescending(s => s.Title);
                    break;
                case "date":
                    movies = movies.OrderBy(s => s.ReleaseDate);
                    break;
                case "date_desc":
                    movies = movies.OrderByDescending(s => s.ReleaseDate);
                    break;
                case "genre":
                    movies = movies.OrderBy(s => s.Genre);
                    break;
                case "genre_desc":
                    movies = movies.OrderByDescending(s => s.Genre);
                    break;
                case "price":
                    movies = movies.OrderBy(s => s.Price);
                    break;
                case "price_desc":
                    movies = movies.OrderByDescending(s => s.Price);
                    break;
                default:
                    movies = movies.OrderBy(s => s.Title);
                    break;
            }
            return View(movies.ToPagedList(pageNum ?? 1, 3));
            //return View(movies.ToList());
        }
最后我们看一下截图:
MVC5学习系列——排序、过滤、分页_第6张图片

哈哈,今天就写到这里吧!谢谢!
代码下载:http://download.csdn.net/download/duyelang/9432384

你可能感兴趣的:(MVC学习系列)

@Html.ActionLink("电影名称", "Index", new { sortOrder = ViewBag.TitleSortParm, searchMovieTitle = ViewData["searchMovieTitle"], searchMovieGenre = ViewData["searchMovieGenre"] }) @Html.ActionLink("发布日期", "Index", new { sortOrder = ViewBag.ReleaseDateSortParm, searchMovieTitle = ViewData["searchMovieTitle"], searchMovieGenre = ViewData["searchMovieGenre"] }) @Html.ActionLink("体裁", "Index", new { sortOrder = ViewBag.GenreSortParm, searchMovieTitle = ViewData["searchMovieTitle"], searchMovieGenre = ViewData["searchMovieGenre"] }) @Html.ActionLink("票价", "Index", new { sortOrder = ViewBag.PriceSortParm, searchMovieTitle = ViewData["searchMovieTitle"], searchMovieGenre = ViewData["searchMovieGenre"] })