Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 710
IAmGroot Avatar asked Dec 07 '22 14:12

IAmGroot


1 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).

like image 72
Darin Dimitrov Avatar answered Jan 02 '23 13:01

Darin Dimitrov