ASP.NET MVC 2入門演練 6 —— 分頁查詢資料

來源:互聯網
上載者:User

這裡只是把List改造了一下。

1、在List.aspx 的列表上方加了如下代碼:

<form id="frmCreate" action="<%=Url.Action("List","News")%>" method="post">
    <%: Html.DropDownListFor(m => new CMSNews().NewsCategory, new SelectList(new MVC2Demo.Models.MVCDemoEntities().CMSNewsCategory.ToList(),
                                "CategoryCode", "CategoryName"),"==Select==")%>
    <input type="submit" value="Search" />

</form>

2、修改List.aspx中的分頁代碼

<div class="pager">
        <%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, "List", new { NewsCategory = ViewData["Category"] })%>
    </div>

List是NewsController中的Action,new { NewsCategory = ViewData["Category"] }是List這個Action中對應的參數NewsCategory的賦值,也就是說我將List這個Action也修改了一下,多加了一個參數NewsCategory ,所以再多加參數,只需要在new後面的大括弧中加就行,用“,”間隔,這應該就是C#3.0中的對象初始化器。
3、修改NewsController的List這個Action

/// <summary>
        /// List
        /// 寫的比較倉促,讀者根據需要修改
        /// </summary>
        /// <param name="page">頁碼</param>
        /// <param name="NewsCategory">跟前台DropDownList的ID是同名的,也就是這裡<%: Html.DropDownListFor(m => new CMSNews().NewsCategory</param>
        /// <returns></returns>
        public ActionResult List(int? page, String NewsCategory)
        {
            //用ViewData["Category"]儲存DropDownList選中項的值

            ViewData["Category"] = NewsCategory;
            //每頁顯示的記錄數
            const int defaultPageSize = 1;
            int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            if(!String.IsNullOrEmpty(NewsCategory))
            {
                return View(db.CMSNews.Where(Model => Model.NewsCategory == NewsCategory).OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
            }
            else
            {
                return View(db.CMSNews.OrderByDescending(Model => Model.PubDate).ToList().ToPagedList(currentPageIndex, defaultPageSize));
            }
        }

這裡用ViewData["Category"]來儲存DropDownList中選中項的值,由於MVCPaging是用Url來翻頁,如果不這樣做,將無法保持DropDownList選中項的值,或者還有其他方法,暫時還沒研究到。

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.