ASP.NET - MVC - Kết hợp tìm kiếm ,sắp xếp, phân trang
Kết hợp tìm kiếm, sắp xếp, và phân trang
Sau khi học các chức năng sắp xếp, tìm kiếm và phân trang ở các bài viết trước, bạn sẽ học cách gom các chức năng này lại trong ASP.NET MVC. Cách đơn giản nhất là gom hết code lại là dự án web của bạn có thể hoạt động theo ý muốn, nhưng bạn lưu ý đây chỉ là cách nghiệp dư. Một số lập trình viên lâu năm thường viết các đoạn code này ở 1 thư viện (hay 1 lớp nào đó) và khi cần chỉ nhúng vài dòng code là xong. Vì bạn là người mới học ASP.NET MVC, cho nên bài này sẽ trình bày cách gom code lại trước.
Bây giờ ta sẽ tiến hành từng phần, trong phương thức Index chúng ta thêm các tham số: public ActionResult Index(int? size, int? page, string sortProperty, string searchString, string sortOrder = "", int categoryID=0)
- Bổ sung code trang tìm kiếm :
Tham số và code trong phương thức Index của trang tìm kiếm:
public ActionResult Index(int? size, int? page, string sortProperty, string searchString, string sortOrder = "", int categoryID=0)
{
// 1. Đoạn code dùng để tìm kiếm
// 1.1. Lưu tư khóa tìm kiếm
ViewBag.Keyword = searchString;
//1.2 Lưu chủ đề tìm kiếm
ViewBag.Subject = categoryID;
//1.2.Tạo câu truy vấn kết 3 bảng Book, Author, Category
var books = db.Books.Include(b => b.Author).Include(b => b.Category);
//1.3. Tìm kiếm theo searchString
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.4. Tìm kiếm theo CategoryID
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.5. Tìm kiếm theo CategoryID
if (categoryID != 0)
books = books.Where(c => c.CategoryID == categoryID);
//1.6. Tìm kiếm theo Danh sách chủ đề
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName"); // danh sách Category
.................
}
Kế tiếp bổ sung code tìm kiếm cho trang index.cshtml
<!-- Đoạn cần thêm -->
@using (Html.BeginForm("Index", "Book", FormMethod.Get, new { @class = "form-inline" }))
{
<div class="form-group">
<label>Chủ đề:</label>@Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" }) <label>Tên sách: </label>
<input type="Text" class="form-control mx-sm-3" value="@ViewBag.Keyword" name="searchString" placeholder="Nhập tên sách cần tìm">
<input type="submit" class="btn btn-danger" value="Tìm sách">
</div><hr />
}
<!-- Kết thúc -->
- Bổ sung code trang sắp xếp
public ActionResult Index(int? size, int? page, string sortProperty, string searchString, string sortOrder = "", int categoryID=0)
{
// 1. Đoạn code dùng để tìm kiếm
// 1.1. Lưu tư khóa tìm kiếm
ViewBag.Keyword = searchString;
//1.2 Lưu chủ đề tìm kiếm
ViewBag.Subject = categoryID;
//1.2.Tạo câu truy vấn kết 3 bảng Book, Author, Category
var books = db.Books.Include(b => b.Author).Include(b => b.Category);
//1.3. Tìm kiếm theo searchString
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.4. Tìm kiếm theo CategoryID
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.5. Tìm kiếm theo CategoryID
if (categoryID != 0)
books = books.Where(c => c.CategoryID == categoryID);
//1.6. Tìm kiếm theo Danh sách chủ đề
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName"); // danh sách Category
// 2 Đoạn code này dùng để sắp xếp
// 2.1. Tạo biến ViewBag gồm sortOrder, searchValue, sortProperty và page
if (sortOrder == "asc") ViewBag.SortOrder = "desc";
if (sortOrder == "desc") ViewBag.SortOrder = "";
if (sortOrder == "") ViewBag.SortOrder = "asc";
// 2.1. Tạo thuộc tính sắp xếp mặc định là "Title"
if (String.IsNullOrEmpty(sortProperty)) sortProperty = "Title";
// 2.2. Sắp xếp tăng/giảm bằng phương thức OrderBy sử dụng trong thư viện Dynamic LINQ
if (sortOrder == "desc")
books = books.OrderBy(sortProperty + " desc");
else
books = books.OrderBy(sortProperty);
....................
}
Kế tiếp bổ sung code sắp xếp cho trang index.cshtml
<!-- Đoạn cần thêm -->
@Html.ActionLink("Tên sách", "Index", new { sortProperty = "Title", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
<!-- Kết thúc -->
</th>
<th>
@Html.ActionLink("Đơn giá", "Index", new { sortProperty = "Price", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
@Html.ActionLink("Ngày xuất bản", "Index", new { sortProperty = "Published", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
@Html.ActionLink("Tác giả", "Index", new { sortProperty = "AuthorID", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
Chủ đề
</th>
<th>
Hình ảnh
</th>
<!-- Kết thúc -->
- Bổ sung code trang phân trang và toàn bộ code phương thức Index:
public ActionResult Index(int? size, int? page, string sortProperty, string searchString, string sortOrder = "", int categoryID=0)
{
// 1. Đoạn code dùng để tìm kiếm
// 1.1. Lưu tư khóa tìm kiếm
ViewBag.Keyword = searchString;
//1.2 Lưu chủ đề tìm kiếm
ViewBag.Subject = categoryID;
//1.2.Tạo câu truy vấn kết 3 bảng Book, Author, Category
var books = db.Books.Include(b => b.Author).Include(b => b.Category);
//1.3. Tìm kiếm theo searchString
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.4. Tìm kiếm theo CategoryID
if (!String.IsNullOrEmpty(searchString))
books = books.Where(b => b.Title.Contains(searchString));
//1.5. Tìm kiếm theo CategoryID
if (categoryID != 0)
books = books.Where(c => c.CategoryID == categoryID);
//1.6. Tìm kiếm theo Danh sách chủ đề
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName"); // danh sách Category
// 2 Đoạn code này dùng để sắp xếp
// 2.1. Tạo biến ViewBag gồm sortOrder, searchValue, sortProperty và page
if (sortOrder == "asc") ViewBag.SortOrder = "desc";
if (sortOrder == "desc") ViewBag.SortOrder = "";
if (sortOrder == "") ViewBag.SortOrder = "asc";
// 2.1. Tạo thuộc tính sắp xếp mặc định là "Title"
if (String.IsNullOrEmpty(sortProperty)) sortProperty = "Title";
// 2.2. Sắp xếp tăng/giảm bằng phương thức OrderBy sử dụng trong thư viện Dynamic LINQ
if (sortOrder == "desc")
books = books.OrderBy(sortProperty + " desc");
else
books = books.OrderBy(sortProperty);
// 3 Đoạn code sau dùng để phân trang
ViewBag.Page = page;
// 3.1. Tạo danh sách chọn số trang
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "5", Value = "5" });
items.Add(new SelectListItem { Text = "10", Value = "10" });
items.Add(new SelectListItem { Text = "20", Value = "20" });
items.Add(new SelectListItem { Text = "25", Value = "25" });
items.Add(new SelectListItem { Text = "50", Value = "50" });
items.Add(new SelectListItem { Text = "100", Value = "100" });
items.Add(new SelectListItem { Text = "200", Value = "200" });
// 3.2. Thiết lập số trang đang chọn vào danh sách List<SelectListItem> items
foreach (var item in items)
{
if (item.Value == size.ToString()) item.Selected = true;
}
ViewBag.Size = items;
ViewBag.CurrentSize = size;
// 3.3. Nếu page = null thì đặt lại là 1.
page = page ?? 1; //if (page == null) page = 1;
// 3.4. Tạo kích thước trang (pageSize), mặc định là 5.
int pageSize = (size ?? 5);
ViewBag.pageSize = pageSize;
// 3.5. Toán tử ?? trong C# mô tả nếu page khác null thì lấy giá trị page, còn
// nếu page = null thì lấy giá trị 1 cho biến pageNumber.
int pageNumber = (page ?? 1);
// 3.6 Lấy tổng số record chia cho kích thước để biết bao nhiêu trang
int checkTotal = (int)(books.ToList().Count / pageSize) + 1;
// Nếu trang vượt qua tổng số trang thì thiết lập là 1 hoặc tổng số trang
if (pageNumber > checkTotal) pageNumber = checkTotal;
// 4. Trả kết quả về Views
return View(books.ToPagedList(pageNumber, pageSize));
}
Kế tiếp bổ sung code phân trang cho trang index.cshtml
<!-- Thêm mã phân trang -->
<br />
<div class="row">
<div class="col-md-6 col-lg-6 col-xs-6 col-sm-6">
@using (Html.BeginForm("Index", "Book", FormMethod.Get))
{
<p>
Kích thước trang: @Html.DropDownList("size", (List<SelectListItem>)ViewBag.Size, new { @onchange = "this.form.submit();" })
</p>
@Html.Hidden("page", (object)ViewBag.Page)
@Html.Hidden("sortProperty", (object)ViewBag.SortProperty)
@Html.Hidden("sortOrder", (object)ViewBag.SortOrder)
@Html.Hidden("searchString", (object)ViewBag.Keyword)
@Html.Hidden("categoryID", (object)ViewBag.Subject)
}
</div>
<div class="col-md-6 col-lg-6 col-xs-6 col-sm-6 text-right">
Trang: @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) / @Model.PageCount
</div>
</div>
@Html.PagedListPager(Model, page => Url.Action("Index", new { page, size = ViewBag.CurrentSize, sortProperty = ViewBag.SortProperty, sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword }))
<!-- Kết thúc -->
Toàn bộ code trang index.cshtml:
@model PagedList.IPagedList<BookStoreManager.Models.Book>
@using PagedList.Mvc;
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Danh sách sách</h2>
<p>
@Html.ActionLink("Thêm sách mới", "Create", null, new { @class = "btn btn-warning" })
</p>
<!-- Đoạn cần thêm -->
@using (Html.BeginForm("Index", "Book", FormMethod.Get, new { @class = "form-inline" }))
{
<div class="form-group">
<label>Chủ đề:</label>@Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" }) <label>Tên sách: </label>
<input type="Text" class="form-control mx-sm-3" value="@ViewBag.Keyword" name="searchString" placeholder="Nhập tên sách cần tìm">
<input type="submit" class="btn btn-danger" value="Tìm sách">
</div><hr />
}
<!-- Kết thúc -->
<table class="table">
<tr>
<th style="width:200px">
<!-- Đoạn cần thêm -->
@Html.ActionLink("Tên sách", "Index", new { sortProperty = "Title", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
<!-- Kết thúc -->
</th>
<th>
@Html.ActionLink("Đơn giá", "Index", new { sortProperty = "Price", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
@Html.ActionLink("Ngày xuất bản", "Index", new { sortProperty = "Published", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
@Html.ActionLink("Tác giả", "Index", new { sortProperty = "AuthorID", sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword, categoryID = ViewBag.Subject })
</th>
<th>
Chủ đề
</th>
<th>
Hình ảnh
</th>
<!-- Kết thúc -->
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Published)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author.AuthorName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Category.CategoryName)
</td>
<td>
<img src="~/bookimages/@item.Images" />
</td>
<td>
@Html.ActionLink("Sửa", "Edit", new { id = item.BookID }) |
@Html.ActionLink("Xem", "Details", new { id = item.BookID }) |
@Html.ActionLink("Xóa", "Delete", new { id = item.BookID })
</td>
</tr>
}
</table>
<!-- Thêm mã phân trang -->
<br />
<div class="row">
<div class="col-md-6 col-lg-6 col-xs-6 col-sm-6">
@using (Html.BeginForm("Index", "Book", FormMethod.Get))
{
<p>
Kích thước trang: @Html.DropDownList("size", (List<SelectListItem>)ViewBag.Size, new { @onchange = "this.form.submit();" })
</p>
@Html.Hidden("page", (object)ViewBag.Page)
@Html.Hidden("sortProperty", (object)ViewBag.SortProperty)
@Html.Hidden("sortOrder", (object)ViewBag.SortOrder)
@Html.Hidden("searchString", (object)ViewBag.Keyword)
@Html.Hidden("categoryID", (object)ViewBag.Subject)
}
</div>
<div class="col-md-6 col-lg-6 col-xs-6 col-sm-6 text-right">
Trang: @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) / @Model.PageCount
</div>
</div>
@Html.PagedListPager(Model, page => Url.Action("Index", new { page, size = ViewBag.CurrentSize, sortProperty = ViewBag.SortProperty, sortOrder = ViewBag.SortOrder, searchString = ViewBag.Keyword }))
<!-- Kết thúc -->
Sau đó, bạn build dự án và chạy đường dẫn http://localhost:45033/Book để xem kết quả, thử nghiệm 1 số chức năng để kiểm tra xem hoạt động đúng hay không.