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?
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With