I am trying to create an extension method. But I get:
No Overload for method
MRUrltakes 0 arguments
HtmlHelper.cs:
namespace MyNS.Helpers
{
public class MyHelper
{
public static string MRUrl(this UrlHelper url)
{
return "blah"
}
}
}
View:
@MyNS.Helpers.MyHelper.MRUrl()
You are not calling the extension method correctly. It should be:
Please read about how extension methods work in C# before using them: http://msdn.microsoft.com/en-us/library/bb383977.aspx
An extension method extends a given type (
UrlHelperin your case) and is invoked on an instance of this type. So since inside your view you already have an instance ofUrlHelper(throughout theUrlproperty) and so you can directly invoke your extension method on it.Before being able to invoke an extension method you need to bring it into scope by adding the namespace in which its containing class is defined:
Also extension methods must be declared inside a static class. Your C# code won’t even compile. So fix it:
All that’s standard C#, nothing to do with ASP.NET MVC or Razor.
Now something ASP.NET MVC specific: if you want to avoid the need of having to bring the namespace into scope into each view (
@using MyNS.Helpers) you could add it to the<namespaces>tag of your~/Views/web.configfile (not to be confused with the~/web.config).