다음은 HTML 도우미 파일 (PageHelper.cs)의 전체 소스이며 완벽하게 작동합니다. ASP.NET MVC 3을 배우고 aPress의 'Pro ASP.NET MVC 3 Framework'서적을 사용하고 있습니다. 나는 책의 흐름을 좋아하지만, 많은 것을 배우고 있습니다. 그러나 지금은 왜 작동하는지에 대한 설명없이 작동 코드를 제공하고 있습니다. 이것이이 예제 중 하나입니다. 이 사이트에서 Google 및 Stack과 상당한 시간을 보냈습니다. 이제 요점을 ...페이지 링크 생성을위한 HTML 도우미 - 이해하려고 시도합니다.
나는 'public static MvcHtmlString PageLinks'에서 일어나는 일의 흐름을 누군가가 설명 할 수 있기를 희망합니다. 나는 이것을 배우려고 노력하고 있으며, 단순히 책을 따라 가지 않고있다. (참고 : 코드의 과도한 주석은 내 자신의 것이며, 학습을 강화하기위한 것이다.)
내 생각은 입니다. MvcHtmlString은 결과 HTML이 이미 있기 때문에 브라우저에 다시 HTML을 다시 인코딩하지 않도록 지시하는 데 사용됩니다. 이은 사용자가 현재있는 페이지를 캡처하는 데 사용됩니다. html은 HtmlHelper 클래스의 인스턴스입니다. (비록 html는 다시 언급되지 않습니다 - 왜 그런가요?). pagingInfo은 반환 된 HTML 생성에 사용 된 속성을 보유하고있는 PagingInfo 클래스의 인스턴스입니다. 여기에 내 머리를 전혀 감쌀 수없는 부분이 있습니다 .... Func 부분. 이 책에서는 Func 매개 변수가 다른 페이지를 볼 수있는 링크를 생성하는 데 사용되는 위임자를 전달할 수있는 기능을 제공한다고 설명합니다.이 기능의 의미와 기능 경로가 필요한 이유를 알 수 없습니다.
나머지 코드는 제가 따라갈 수 있습니다. 장황한 게시물에 대해 유감스럽게 생각하지만 선명도를 찾고 있습니다. 내 코드 주석이나 설명이 올바르지 않으면 수정하십시오. 미리 감사드립니다! 난 그냥 MVC 3를 배우면서 같은 책에서이 코드를 작성했다
using System;
using System.Text;
using System.Web.Mvc;
using SportsStore.WebUI.Models;
//You use HTML helpers in a view to render HTML content. An HTML helper, in most
//cases, is just a method that returns a string. You can build an entire ASP.NET
//MVC application without using a single HTML helper. However, HTML helpers make
//your life as a developer easier. By taking advantage of helpers, you can build
//your views with far less work. Write once, reuse often.
//We use 'MvcHtmlString' so that the result doesn't get re-encoded in the view.
//It is part of the MVC framework and when you create your own HTML helper
//methods like this one, always use it.
namespace SportsStore.WebUI.HtmlHelpers
{
//This is public so it can be accessed in other areas, however the 'static'
//means it can't be instantiated.
public static class PagingHelpers
{
//This is an HTML Helper method that we call 'PageLinks', which generates
//HTML for a set of page links using the info provided in a PagingInfo
//object. Remember that extension methods are only available for use
//when the namespace that contains it is in scope. In a code file, this
//is done with a 'using' statement, but for a Razor view, we must add a
//configuration entry to the View-specific Web.config file OR add a
//'@using' statement to the view itself. For this project we chose to
//use the Web.config file to keep the View less cluttered.
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageUrl)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a"); //Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.Append(tag.ToString());
}**
return MvcHtmlString.Create(result.ToString());
}
}
}