【问题标题】:View model does not recognize extension method?视图模型不识别扩展方法?
【发布时间】:2013-03-08 08:14:12
【问题描述】:

我的视图中有一个 Html.GlobalisedPageLinks 扩展方法,但得到一条红线说明我的视图模型不包含该方法并且我有一些无效参数?

这里是一行:

<div class="actions-left">
  <%= Html.GlobalisedPageLinks(Amico.Web.Mvc.Extensions.Enums.PageLinksFormat.Empty, Model.CurrentPage, Model.PageSize, Model.Total, x => Url.Action("Index", "Scorm", new { area = "Admin", page = x }))%>
</div>

扩展方法:

public static string GlobalisedPageLinks(this HtmlHelper html, Amico.Web.Mvc.Extensions.Enums.PageLinksFormat format, int currentPage, int pageSize, int totalResults, Func<int, string> pageUrl)
{
  int totalPages = Math.Max(Convert.ToInt32(Math.Ceiling((double)totalResults / pageSize)), 1);

  int startresult = ((Math.Max(1, currentPage) - 1) * pageSize) + 1;
  int endresult = Math.Min(startresult + (pageSize - 1), totalResults);

  string pagesText = html.Resource(Resources.Global.PageLinks.PageLinksFormatPages, currentPage, totalPages);
  string resultsText = html.Resource(Resources.Global.PageLinks.PageLinksFormatResults, startresult, endresult, totalResults);
  string firstText = html.Resource(Resources.Global.PageLinks.First);
  string previousText = html.Resource(Resources.Global.PageLinks.Previous);
  string nextText = html.Resource(Resources.Global.PageLinks.Next);
  string lastText = html.Resource(Resources.Global.PageLinks.Last);

  return "<span class='page-links'>" + html.PageLinks(format, currentPage, pageSize, totalResults, pageUrl,
    pagesText, resultsText, firstText, previousText, nextText, lastText) + "</span>";
}

我错过了什么? 谢谢

【问题讨论】:

    标签: asp.net-mvc-3 extension-methods


    【解决方案1】:

    你需要在你的视图中添加一条 using 语句到包含扩展方法的类中:

    @using Amico.Web.Mvc.Extensions.YourExtensionClass
    

    如果您需要在许多视图中访问此扩展类,您还可以在您的视图文件夹中的 web.Config 中将其命名空间添加为已知命名空间(此示例适用于 MVC3,对于 MVC4,主机将有所不同) :

    <system.web.webPages.razor>
      <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <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="Amico.Web.Mvc.Extensions" />
        </namespaces>
      </pages>
    </system.web.webPages.razor>
    

    【讨论】:

    • 我的视图文件夹确实有一个 web.config 但它是包含该命名空间的主 web.config 所以现在我不知道 :)
    • 如果显式添加 using 语句会发生什么?
    • 我可以这样做,但如果我这样做,老板将无法通过我的代码审查!大声笑让我快问他:)
    • 您需要将页面命名空间添加到您的视图文件夹中 Web.config 中的 pages 部分,而不是主 Web.config。查看我更新的答案 - 如果您没有那个 Web.config,您可以添加它:)
    猜你喜欢
    • 1970-01-01
    • 2011-02-05
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多