Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 273
Todd Davis Avatar asked Jun 06 '13 02:06

Todd Davis


1 Answers

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>
}
like image 188
Rowan Freeman Avatar answered Sep 22 '22 20:09

Rowan Freeman