【问题标题】:How value passed to this lambda值如何传递给这个 lambda
【发布时间】:2014-07-14 15:19:58
【问题描述】:

我正在尝试 ASP.NET MVC 4 中的示例。他为 HtmlHelper 创建了一个扩展方法。下面是代码:

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.Append(tag.ToString());
        }
        return MvcHtmlString.Create(result.ToString());
    }
}

这被以下视图使用:

@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, category = Model.CurrentCategory }))

这是定义视图操作方法的控制器:

public ViewResult List(string category, int page = 1)
{
    ProductsListViewModel model = new ProductsListViewModel {
        Products = repository.Products
            .Where(p => category == null || p.Category == category)
            .OrderBy(p => p.ProductID)
            .Skip((page - 1) * PageSize)
            .Take(PageSize),
        PagingInfo = new PagingInfo
        {
            CurrentPage = page,
            ItemsPerPage = PageSize,
            TotalItems = repository.Products.Count()
        },
        CurrentCategory = category
    };
    return View(model);
}

根据扩展方法(并使用断点)的结果,x 的值是控制器中 List 操作方法上的“页面”参数。 x 是如何得到它的?或者值是如何传递给 x 的?在处理集合时,我主要在 LINQ 上使用委托。作为参数传递的值来自集合(迭代)。但我似乎无法理解这一点。

【问题讨论】:

    标签: asp.net-mvc lambda


    【解决方案1】:

    基本上Func&lt;int, string&gt; pageUrl 表示一个具有一个 int 参数并且返回字符串的函数。

    您在for loop 中通过以下方式调用此函数:

    tag.MergeAttribute("href", pageUrl(i));
    

    当您调用 pageUrl 时,它基本上会调用类似:

    public String SomeFunction(int x)
    {
      return Url.Action("List", new { page = x, category = Model.CurrentCategory });
    }
    

    所以 x =&gt; Url.Action("List", new { page = x, category = Model.CurrentCategory }) 这里的意思是匿名函数,它只是包装了 Url.Action 函数

    【讨论】:

    • 哇,我不敢相信我没有看到行 tag.MergeAttribute("href", pageUrl(i))。谢谢!
    【解决方案2】:

    PagingHelpers.PageLinks 扩展方法是使用Func&lt;int, string&gt; 生成 URL。

    由于实际生成URL是由View提供的,而不是扩展方法,扩展方法只是利用view中定义的机制作为URL生成器。

    扩展方法是这样工作的:

    • 我在 1 和页数之间循环
    • 我生成了一个由传递给我的Func&lt;int, string&gt; 定义的链接
      • (注意我不在乎它是如何工作的,只要我给它一个int 并返回一个string
    • 我在href 中使用它。

    所以看视图:

    @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, category = Model.CurrentCategory }))
    

    Func&lt;int, string&gt; 是在说“当我得到一个 int x 时,用它调用这个代码”。这样,URL 生成由视图控制。扩展方法只对Url.Action 生成的 HTML 感兴趣。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多