2

我想在视图之间共享从 mediaPart 创建 img 标记的逻辑。我已经创建了以下剃须刀helper方法:

@helper CreateImgFromMediaPart(dynamic mediaPart, int width = 150)
{
    var imgSrc = mediaPart != null ? mediaPart.MediaUrl : string.Empty;
    var imgAlt = mediaPart != null ? mediaPart.AlternateText : string.Empty;
    <img alt="@imgAlt" src="@imgSrc" />
}

我通过创建一个 App_Code 文件夹,将 MyHelpers.cshtml 文件放入其中,并将上述辅助方法放入该文件来尝试此操作。不幸的是,我们收到以下错误:

当前上下文中不存在名称“MyHelpers”。

4

2 回答 2

1

您是否在视图文件夹中添加了对 web.config 的 dll 引用?这是用于解决剃刀特定的帮助程序/定义的内容。

于 2014-08-22T01:52:30.193 回答
1

迈克比勒的回答奏效了。这是我添加到 Views 文件夹中的 web.config。

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <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>
        <!-- This is the key line -->
        <add namespace="MyBase.Namespace.Extensions" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>
于 2014-08-22T02:15:17.493 回答