以下は、HTML ヘルパー ファイル (PageHelper.cs) の完全なソースであり、完全に機能します。私はASP.NET MVC 3を学んでおり、aPressの「Pro ASP.NET MVC 3 Framework」の本を使用しています。私は本の流れが大好きで、多くのことを学んでいますが、時々、それが機能する理由についての実際の説明なしに機能するコードを提供します。これはこれらの例の 1 つです。私はこれについて、Google と Stack でかなりの時間を費やしてきました。今すぐ本題に入るには...
「public static MvcHtmlString PageLinks」内で何が起こっているかの流れを誰かが説明できることを願っています。私はこれを学ぼうとしており、単に本を追うのではありません (注: コード内の過度のコメントは私自身のものであり、学習を強化するためのものです)。
私の見解では、MvcHtmlStringは、結果の HTML が既に再エンコードされているため、ブラウザーに HTML を再度エンコードしないように指示するために使用されます。 これは、ユーザーが現在いるページをキャプチャするために使用されます。 htmlはHtmlHelperクラスのインスタンス化ですか? ( htmlは二度と言及されませんが、それはなぜですか?)。 pagingInfoは、返される HTML 作成で使用されるプロパティを保持するPagingInfoクラスのインスタンス化です。ここは、私がまったく理解できない部分です.... Funcの部分です。この本はFuncがパラメータは、他のページを表示するためのリンクを生成するために使用されるデリゲートを渡す機能を提供します-これが何を意味するのか、なぜ関数ルートが必要なのかまったくわかりません.
私が従うことができる残りのコード。長々とした投稿で申し訳ありませんが、明確にしたいと思います。コードのコメントや説明が間違っている場合は、修正してください。前もって感謝します!
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());
}
}
}