ASP.Net MVC3: UrlHelper Extension method requires argument

I am trying to create an extension method. But I get:

No Overload for method MRUrl takes 0 arguments

HtmlHelper.cs:

namespace MyNS.Helpers
{
   public class MyHelper
   {
    public static string MRUrl(this UrlHelper url)
    {
         return "blah"
    }
  }
}

View:

@MyNS.Helpers.MyHelper.MRUrl()

Answers


You are not calling the extension method correctly. It should be:

@Url.MRUrl()

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 (UrlHelper in your case) and is invoked on an instance of this type. So since inside your view you already have an instance of UrlHelper (throughout the Url property) 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:

@using MyNS.Helpers
@Url.MRUrl()

Also extension methods must be declared inside a static class. Your C# code won't even compile. So fix it:

namespace MyNS.Helpers
{
    public static class HtmlHelper // Bad name choice I know.
    {
        public static string MRUrl(this UrlHelper url)
        {
            return "blah";
        }
    }
}

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.config file (not to be confused with the ~/web.config).


Need Your Help

Count json objects in array

php mysql json

Struggling to get the count of all objects in my array to spit out number in json. Can anyone help?

What is the benefit to using <acronym> and <abbr>?

html xhtml seo accessibility abbr

Should i give my time to change terms and abbreviations to &lt;acronym&gt; and &lt;abbr&gt;? Is it worth to use? What are pros to use both tags? Is it useful for SEO and screen reader?