The name 'Url' does not exist in the current context error

Todd Davis picture Todd Davis · Jun 6, 2013 · Viewed 7.3k times · Source

I have an MVC4 project that I am trying to create a helper for. I have added a folder called "App_Code", and in that folder I added a file called MyHelpers.cshtml. Here are the entire contents of that file:

@helper MakeButton(string linkText, string actionName, string controllerName, string iconName, string classes) {
    <a href='@Url.Action(linkText,actionName,controllerName)' class="btn @classes">Primary link</a>
}

(I know there are some unused params, I'll get to those later after I get this fixed)

I "cleaned" and built the solution, no errors.

In the page that uses the helper, I added this code.

@MyHelpers.MakeButton("Back","CreateOffer","Merchant","","btn-primary")

When I attempt to run the project, I get the following error:

Compiler Error Message: CS0103: The name 'Url' does not exist in the current context

I can't seem to find the correct way to write this - what am I doing wrong? It seems to be correct as compared to examples I've seen on the web?

Answer

Rowan Freeman picture Rowan Freeman · Jun 6, 2013

As JeffB's link suggests, your helper file doesn't have access to the UrlHelper object.

This is an example fix:

@helper MakeButton(string linkText, string actionName,
    string controllerName, string iconName, string classes) {

    System.Web.Mvc.UrlHelper urlHelper =
        new System.Web.Mvc.UrlHelper(Request.RequestContext);
    <a href='@urlHelper.Action(linkText,actionName,controllerName)'
        class="btn @classes">Primary link</a>
}