1

I created a String extension method. It is under the namespace MyApp. It worked in all C# classes, but won't work in MVC Razor views.

I tried adding to one and both Web.config files (on in root, and one is views), under the <namespaces> sections, but it just won't find the extension method. I tried adding under the <system.web> and <system.web.webPages.razor> sections, but still won't work.

I am using MVC 3, .Net 4.

Here's the extension:

namespace MyApp
{    
    public static class StringExtension
    {
        // ...
        [DebuggerStepThrough]
        public static string FormatWith(this string target, params object[] args)
        {
            Check.Argument.IsNotEmpty(target, "target");

            return string.Format(Constants.CurrentCulture, target, args);
        }
    }
}

Here's the web.config piece:

<namespaces>
    <!-- The extension method is in this namespace: -->
    <add namespace="MyApp" />
</namespaces>

And:

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="MyApp" />
      <add namespace="MyApp.Web" />
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

The error I keep getting is:

'string' does not contain a definition for 'FormatWith' and no extension method 'FormatWith' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

I tried adding @using MyApp at the top of the view, but it still shows same error.

I have used this extension in a nearly identical project using the same approach and it works fine. The other project is MVC 4 and .net 4.5.

Swisher Sweet
  • 769
  • 11
  • 33
  • Is the method & class `public`? – SLaks Jan 14 '18 at 21:00
  • Yes. I updated the question. – Swisher Sweet Jan 14 '18 at 21:15
  • 2
    Just to troubleshoot that it is even accessable add the `using ` to the top of the view and see if the extension is available. if yes then we can move forward from there. – Nkosi Jan 14 '18 at 21:38
  • Also show the `` as it is now in the `Views/web.config` file – Nkosi Jan 14 '18 at 21:39
  • 1
    Take a look at this. https://stackoverflow.com/questions/19255688/why-is-extension-method-not-found-in-mvc4-razor-view?rq=1 – Nkosi Jan 14 '18 at 21:42
  • I updated question. I have added the `using MyApp` to the view, and it still won't find the extension method. However, the controller for the view finds the extension just fine. – Swisher Sweet Jan 15 '18 at 14:43

0 Answers0