[번역] ASP.NET MVC 3 개발의 20가지 노하우 (7) [20 Recipes for Programming MVC 3]: 목록 정렬

11421 단어 programming
의제
현재 매우 큰 목록(예를 들어 도서 목록)이 하나 있는데, 어떤 것을 찾으려면 매우 어렵다.목록의 항목을 정렬하면 검색에 도움이 될 것입니다.
 
솔루션
책 목록 목록의 열 제목을 링크로 업데이트하고, 링크가 눌렸을 때, 선택한 열의 내용을 링크로 정렬합니다. (제목 링크를 다시 눌러서 오름차순, 내림차순으로 전환합니다.)
 
토론
내가 이전에 사용했던 프레임에 비해 정렬을 추가하고 보기를 자동으로 생성하는 과정이 놀랍다.외부의 MVC 버전에서 전체적인 프레임의 일부가 됐으면 좋겠다.ASP 참조.NET MVC의 사이트 첫 페이지에서 예를 들면, 우리는Switch 문구를 정의해야 하며, 각 열의 정렬 상황은 Case를 복제해서 실현해야 한다.다행히 우리의 이 사례 중에는 다섯 항목만 순서를 정해야 하기 때문에 상황이 그리 나쁘지 않다.나중에 작성자나 다른 열과 같은 정렬이 필요한 경우 이 Case를 복사하면 됩니다.다음 예에서는 Dynamic Linq Library를 사용하여 작업을 단순화합니다.
Linq library는 데이터베이스에서 강력한 유형의 결과를 조회하고 반환할 수 있습니다.프로그래밍 도구는 스마트 감지 지원과 컴파일링 시 오류 감지 등 다양한 기능을 바탕으로 조작할 수 있습니다.
Books Controller 컨트롤러 및 Books, Index 뷰에 정렬 생성 지원을 추가합니다.Index 뷰의 코드는 다음과 같습니다.
@model IEnumerable<MvcApplication4.Models.Book>
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink((string)ViewBag.CreateLink, "Create")
</p>

<table>
<tr>
<th>
@Html.ActionLink((string)ViewBag.TitleDisplay,
"Index", new { sortOrder = ViewBag.TitleSortParam })
</th>
<th>
@Html.ActionLink((string)ViewBag.IsbnDisplay,
"Index", new { sortOrder = ViewBag.IsbnSortParam })
</th>
<th>
@ViewBag.SummaryDisplay
</th>
<th>
@Html.ActionLink((string)ViewBag.AuthorDisplay,
"Index", new { sortOrder = ViewBag.AuthorSortParam })
</th>
<th>
@ViewBag.ThumbnailDisplay
</th>
<th>
@Html.ActionLink((string)ViewBag.PriceDisplay,
"Index", new { sortOrder = ViewBag.PriceSortParam })
</th>
<th>
@Html.ActionLink((string)ViewBag.PublishedDisplay,
"Index", new { sortOrder =
ViewBag.PublishedSortParam })
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Isbn)
</td>
<td>
@Html.DisplayFor(modelItem => item.Summary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Thumbnail)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Published)
</td>
<td>
@Html.ActionLink((string)ViewBag.EditLink,
"Edit", new { id=item.ID }) |
@Html.ActionLink((string)ViewBag.DetailsLink,
"Details", new { id = item.ID }) |
@Html.ActionLink((string)ViewBag.DeleteLink,
"Delete", new { id = item.ID })
</td>
</tr>
}
</table>

위 예에서는 이전에 만들어진th 태그를 수정하고 Html helper를 사용하여 정적 텍스트를 HTML 링크로 변환합니다.
그런 다음 BookController에서 Index 메서드를 수정해야 합니다.이 메서드는 Linq에서 질의를 수행할 때 결과 정렬의 열을 지정하는 새 정렬 매개변수를 적용합니다.각 열의 정렬 기준을 저장할 새 변수가 ViewBag에 생성됩니다.
Microsoft에서 Linq에 대한 새로운 무료 확장 다이나믹Query 클래스를 제공합니다. 이 확장은 실행할 때 검색 문장을 동적으로 생성할 수 있으며, 접근할 수 있습니다.http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspxC# 버전으로 다운로드합니다.다운로드한 후 하드디스크의 어느 위치로 압축을 풀고 디렉터리에서 이 파일을 찾아 프로젝트 프로젝트에 추가합니다. "~\CSharpSamples\LinqSamples\DynamicQuery\DynamicQuery\Dynamic.cs"코드를 더 잘 구성하기 위해서는 프로젝트 프로젝트에서 'Utils' 폴더를 만들고' Utils' 폴더를 오른쪽 단추로 눌러서 '추가' -> '기존 항목' 을 선택한 다음, 탐색 창을 통해 이 동적 클래스를 찾아야 합니다. (또는 'Utils' 디렉터리에 파일을 드래그해서 넣을 수도 있습니다.) 
동적 클래스 추가가 완료되면 편집업데이트Booksctroller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using MvcApplication4.Models;
using MvcApplication4.Resources;

namespace MvcApplication4.Controllers
{
public class BooksController : Controller
{
private BookDBContext db = new BookDBContext();
//
// GET: /Books/
public ViewResult Index(string sortOrder)
{
#region ViewBag Resources

#endregion
#region ViewBag Sort Params
// Define the sort orders - if the same link is
// clicked twice, reverse the direction from
// ascending to descending
ViewBag.TitleSortParam = (sortOrder == "Title")
? "Title desc" : "Title";
ViewBag.IsbnSortParam = (sortOrder == "Isbn")
? "Isbn desc" : "Isbn";
ViewBag.AuthorSortParam = (sortOrder == "Author")
? "Author desc" : "Author";
ViewBag.PriceSortParam = (sortOrder == "Price")
? "Price desc" : "Price";
ViewBag.PublishedSortParam =
(String.IsNullOrEmpty(sortOrder))
? "Published desc" : "";
// Default the sort order
if (String.IsNullOrEmpty(sortOrder))
{
sortOrder = "Published desc";
}
#endregion
var books = db.Books.OrderBy(sortOrder);
return View(books.ToList());
}
...
}

}

참고 자료
System.Linq.Expressions 이름 공간 원서 주소 책 원본 코드

좋은 웹페이지 즐겨찾기