下面是我的 HTML 帮助文件 (PageHelper.cs) 的完整源代码,它运行良好。我正在学习 ASP.NET MVC 3 并使用 aPress 的“Pro ASP.NET MVC 3 Framework”一书。我喜欢这本书的流程,并且学到了很多东西,但是它时不时地提供工作代码,但没有真正解释它为什么工作,这就是这些例子之一。我在 Google 和 Stack 上花费了相当多的时间。现在要进入正题...
我希望有人可以解释“公共静态 MvcHtmlString PageLinks”中发生的事情的流程。我正在尝试学习这一点,而不是简单地按照书中的内容进行学习(注意:代码中的过多注释是我自己的 - 旨在加强学习)。
我的看法是MvcHtmlString用于告诉浏览器不要重新编码 HTML,因为生成的 HTML 已经是。 这用于捕获用户当前所在的页面。 html是HtmlHelper类的实例化吗?(虽然html再也没有被提及 - 为什么会这样?)。 pagingInfo是我的PagingInfo类的实例化,它包含在返回的 HTML 创建中使用的属性。这是我完全无法理解的部分...... 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());
}
}
}