5

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?

Todd Davis
  • 5,855
  • 10
  • 53
  • 89
  • 2
    I think you need to do something like this: http://stackoverflow.com/questions/4710853/using-mvc-htmlhelper-extensions-from-razor-declarative-views. – JeffB Jun 06 '13 at 03:35
  • Did you mean to use `@Html.ActionLink` rather than `@Url.Action`? I've put a footnote in my answer about the two. – Andy Brown Jun 06 '13 at 06:26

2 Answers2

4

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>
}
Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100
4

For my helpers I create a base class:

using System.Web.WebPages;
using System.Web.Mvc;

namespace MyProject
{
    public class HelperBase : HelperPage
    {
        public static new HtmlHelper Html
        {
            get { return ((WebViewPage)WebPageContext.Current.Page).Html; }
        }
        public static System.Web.Mvc.UrlHelper Url
        {
            get { return ((WebViewPage)WebPageContext.Current.Page).Url; }
        }
    }
}

And then in my helper I do (to use yours as an example):

@inherits MyProject.HelperBase
@using System.Web.Mvc
@using System.Web.Mvc.Html

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

Also, are you sure you didn't mean to use @Html.ActionLink (via LinkExtensions) instead of @Url.Action? The latter doesn't seem to have a linkText, actionName, controllerName overload, the former does?

Andy Brown
  • 18,961
  • 3
  • 52
  • 62