-->

Why doesn't the compiler find my razor helpers

2019-07-20 16:33发布

问题:

I would like to share among views the logic for creating an img tag from a mediaPart. I have already created the following razor helper method:

@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" />
}

I have tried this by creating an App_Code folder, putting into it a MyHelpers.cshtml file, and putting in that file the above helper method. Unfortunately, we receive the following error:

The name 'MyHelpers' does not exist in the current context.

回答1:

Have you added the dll reference to the web.config in the views folder? This is what is used to resolve razor specific helper/definitions.



回答2:

Mike Beeler's answer worked. This is the web.config that I added to my Views folder.

<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>