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.