我正在关注Pro ASP.Net MVC2书,其中90%的内容对我来说都是新的。我觉得自己像糖果店里的小孩! :)
单元测试,依赖注入和其他事情对我创建的典型CRUD应用程序来说都是新的和非常陌生的。
现在我在测试时遇到问题,本书要求我们设计。
[Test]
public void Can_Generate_Links_To_Other_Pages()
{
// Arrange: We're going to extend the HtmlHelper class.
// It doesn't matter if the variable we use is null.
HtmlHelper html = null;
// Arrange: The helper should take a PagingInfo instance (that's
// a class we haven't yet defined) and a lambda to specify the URLs
PagingInfo pagingInfo = new PagingInfo
{
CurrentPage = 2,
TotalItems = 28,
ItemsPerPage = 10
};
Func<int, string> pageUrl = i => "Page" + i;
// Act
MvcHtmlString result = html.PageLinks(pagingInfo, pageUrl);
// Assert: Here's how it should format the links
result.ToString().ShouldEqual(@"<a href=""Page1"">1</a>
<a class=""selected"" href=""Page2"">2</a>
<a href=""Page3"">3</a>");
}
我的html变量是一个HtmlHelper变量。似乎扩展方法PageLinks()未正确注册。
我会在哪里查看?我意识到这个问题可能有点模糊,但任何帮助都会很棒。
修改
显然这是我注册扩展方法的地方。虽然它似乎没有任何扩展。当我在上面的代码中输入时,至少intellisnse没有显示它。
public static class PagingHelpers
{
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.AppendLine(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
此外,有人可以告诉我如何设置Visual Studio,因此它只是复制纯文本而不是荒谬的缩进吗?
编辑2: Woops!忘了键入错误:
错误1'System.Web.Mvc.HtmlHelper' 不包含的定义 'PageLinks'并没有扩展方法 'PageLinks'接受第一个论点 类型为'System.Web.Mvc.HtmlHelper' 可以找到(你错过了吗? 使用指令或程序集 参考?)C:\ Users \ Sergio \ documents \ visual 工作室 2010 \ Projects \ SportsStore \ SportsStore.UnitTests \ ShowingPageLinks.cs 35 41 SportsStore.UnitTests
答案 0 :(得分:8)
要使用扩展方法,您需要包含扩展方法类所在的命名空间。您还需要确保扩展方法类是静态的并且可以使用代码(例如,如果它在另一个程序集中,则不能是内部的)。最后,请务必不要忘记您要扩展的类型上的this
关键字。如果所有这些都已到位,你就不应该看到问题。
答案 1 :(得分:3)
您可以将命名空间添加到web.config中的所有页面,如下所示:
<system.web>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
<add namespace="YourNameSpace.HtmlHelpers"/>
</namespaces>
</pages>
答案 2 :(得分:0)
使用
MvcHtmlString result = PagingHelpers.PageLinks(myHelper, pagingInfo, pageUrlDelegate);
而不是
MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate);
答案 3 :(得分:0)
您需要在此行的代码上方添加List.cshtml
@model SportsStore.WebUI.Models.ProductsListViewModel
答案 4 :(得分:0)
您可以从PagingHelpers类中的PageLinks方法代码参数中删除this HtmlHelper html,
,并将HtmlHelper替换为PagingHelpers
像这样
MvcHtmlString result = PagingHelpers.PageLinks(pagingInfo, pageUrl);
HtmlHelper
未在您的示例中使用。