.net Core學習筆記2 實現列表的條件篩選,排序,分頁

打開vs,完善上次"簡單粗暴"的項目 bootstrap

發現上次的實體類的導航屬性有點問題,這是更改後的async

namespace ProductMvc.Models
{
    public class ProductType
    {
        public int ID { get; set; }
        public string TypeName { get; set; }

        public ICollection<Product> product { get; set; }//一種類型可能有多個商品,因此是集合     }
}

namespace ProductMvc.Models
{
    public class Product
    {
        public int ID { get; set; }
        public string ProductName { get; set; }

        public DateTime ProductDate { get; set; }

        public decimal Price { get; set; }
        public int TypeID { get; set; }
        public ProductType ProductType { get; set; }
    }
}

爲了列表展現方便我建立了一個專門用於展現的類ide

 public class ProductViewModel
    {
        public int ID { get; set; }
        public string ProductName { get; set; }

        public DateTime ProductDate { get; set; }

        public decimal Price { get; set; }

        public string TypeName { get; set; }
    }

控制器的Index方法也要作相應的修改函數

  public async Task<IActionResult> Index(string SortOrder, string SearchString,int id=1)
        {
            ViewData["DATE_KEY"] = string.IsNullOrEmpty(SortOrder) ? "DATE_KEY" : "";
            ViewData["TYPE_KEY"] = SortOrder == "TYPE_KEY" ? "TYPE_KEY" : "";
            ViewData["SerachName"] = SearchString;
 //鏈接查詢
var products = from t in _context.ProductType from p in _context.Product where t.ID == p.TypeID select new ProductViewModel { ID=p.ID,Price = p.Price, ProductDate = p.ProductDate, ProductName = p.ProductName, TypeName = t.TypeName }; //按條件查詢 if(SearchString!=""&&SearchString!=null) { products = products.Where(p=>p.ProductName.Contains(SearchString)); } //排序 switch(SortOrder) { case "DATE_KEY": products = products.OrderByDescending(p=>p.ProductDate); break; case "TYPE_KEY": products = products.OrderByDescending(p => p.TypeName);//倒序 break; default: products = products.OrderBy(p => p.ID); break; } var pageOption = new PagerInBase { CurrentPage = id,//當前頁數 PageSize = 3, Total = await products.CountAsync(), RouteUrl = "/Products/Index" }; //分頁參數 ViewBag.PagerOption = pageOption; //數據 return View(await products.Skip((pageOption.CurrentPage - 1) * pageOption.PageSize).Take(pageOption.PageSize).ToListAsync()); }

函數中的參數SortOrder用於排序,SearchString條件參數,id爲分頁參數下面是視圖中的代碼(有陰影的是修改過的地方):ui

@model IEnumerable<ProductMvc.Models.ProductViewModel> @addTagHelper "ProductMvc.Models.PagerTagHelper,ProductMvc"
@{
    ViewData["Title"] = "Index";
}

<h2>商 品 列 表</h2>

<p>
    <a asp-action="Create"><input type="button" value="新 建" class="btn btn-default" /></a>
</p>
<form asp-action="Index" method="get">
    <p>名稱:<input  type="text" name="searchString" value="@ViewData["SerachName"]"/>
    <input type="submit" value="搜索"  class="btn btn-default"/>
        </p>
</form>
<table class="table">
    <thead>
        <tr>
                <th>
                    商品名稱
                </th>
                <th>                   
                    <a asp-action="Index" asp-route-SortOrder="@ViewData["DATE_KEY"]">生產日期</a>
                </th>
                <th>
                   價格
                </th>
                <th>
                  <a asp-action="Index" asp-route-SortOrder="@ViewData["TYPE_KEY"]">商品類型</a>
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ProductName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProductDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td> @Html.DisplayFor(modelItem => item.TypeName) </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID">編輯</a> |
                <a asp-action="Details" asp-route-id="@item.ID">詳情</a> |
                <a asp-action="Delete" asp-route-id="@item.ID">刪除</a>
            </td>
        </tr>
}
    </tbody>
</table>
<pager pager-option="ViewBag.PagerOption as PagerInBase"></pager>

分頁標籤是用TagHelper實現的,這個主要是參考 「神牛步行3」  http://www.cnblogs.com/wangrudong003/ 的博客完成的,直接貼代碼,添加類PagerInBasespa

namespace ProductMvc.Models
{
    #region 分頁擴展 PagerInBase

    /// <summary>
    /// 分頁option屬性
    /// </summary>
    public class PagerInBase
    {
        /// <summary>
        /// 當前頁 必傳
        /// </summary>
        public int CurrentPage { get; set; }
        /// <summary>
        /// 總條數 必傳
        /// </summary>
        public int Total { get; set; }

        /// <summary>
        /// 分頁記錄數(每頁條數 默認每頁15條)
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 路由地址(格式如:/Controller/Action) 默認自動獲取
        /// </summary>
        public string RouteUrl { get; set; }

        /// <summary>
        /// 樣式 默認 bootstrap樣式 1
        /// </summary>
        public int StyleNum { get; set; }
    }

    /// <summary>
    /// 分頁標籤
    /// </summary>
    public class PagerTagHelper : TagHelper
    {

        public PagerInBase PagerOption { get; set; }


        public override void Process(TagHelperContext context, TagHelperOutput output)
        {

            output.TagName = "div";

            if (PagerOption.PageSize <= 0) { PagerOption.PageSize = 15; }
            if (PagerOption.CurrentPage <= 0) { PagerOption.CurrentPage = 1; }
            if (PagerOption.Total <= 0) { return; }

            //總頁數
            var totalPage = PagerOption.Total / PagerOption.PageSize + (PagerOption.Total % PagerOption.PageSize > 0 ? 1 : 0);
            if (totalPage <= 0) { return; }
            //當前路由地址
            if (string.IsNullOrEmpty(PagerOption.RouteUrl))
            {

                //PagerOption.RouteUrl = helper.ViewContext.HttpContext.Request.RawUrl;
                if (!string.IsNullOrEmpty(PagerOption.RouteUrl))
                {

                    var lastIndex = PagerOption.RouteUrl.LastIndexOf("/");
                    PagerOption.RouteUrl = PagerOption.RouteUrl.Substring(0, lastIndex);
                }
            }
            PagerOption.RouteUrl = PagerOption.RouteUrl.TrimEnd('/');

            //構造分頁樣式
            var sbPage = new StringBuilder(string.Empty);
            switch (PagerOption.StyleNum)
            {
                case 2:
                    {
                        break;
                    }
                default:
                    {
                        #region 默認樣式

                        sbPage.Append("<nav>");
                        sbPage.Append(" <ul class=\"pagination\">");
                        sbPage.AppendFormat("  <li><a href=\"{0}/{1}\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li>",
                              PagerOption.RouteUrl,
                              PagerOption.CurrentPage - 1 <= 0 ? 1 : PagerOption.CurrentPage - 1);

                        for (int i = 1; i <= totalPage; i++)
                        {

                            sbPage.AppendFormat("  <li {1}><a href=\"{2}/{0}\">{0}</a></li>",
                             i,
                             i == PagerOption.CurrentPage ? "class=\"active\"" : "",
                             PagerOption.RouteUrl);

                        }

                        sbPage.Append("  <li>");
                        sbPage.AppendFormat("   <a href=\"{0}/{1}\" aria-label=\"Next\">",
                             PagerOption.RouteUrl,
                             PagerOption.CurrentPage + 1 > totalPage ? PagerOption.CurrentPage : PagerOption.CurrentPage + 1);
                        sbPage.Append("    <span aria-hidden=\"true\">»</span>");
                        sbPage.Append("   </a>");
                        sbPage.Append("  </li>");
                        sbPage.Append(" </ul>");
                        sbPage.Append("</nav>");
                        #endregion
                    }
                    break;
            }

            output.Content.SetHtmlContent(sbPage.ToString());
        }

    }
    #endregion
}

最後的效果:code

好吧我以爲依然的簡單粗暴,在後期我會不斷的完善的。orm

新手上路,還望大佬們指正blog

相關文章
相關標籤/搜索