Reputation: 1184
I have currently created an extension method
using System.Web;
using System.Web.Mvc;
namespace Mobi.QualityControl.Site.Infrastructure
{
public static class HtmlHelpers
{
public static HtmlString ActionImage(this HtmlHelper htmlHelper, string action, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return new HtmlString(anchorHtml);
}
}
}
I am then trying to use it in my page with the using statement in my web.config and it is picking the method up but it
@HtmlHelpers.ActionImage("Account/Register", "/images/home/gettingstarted.png", "Edit", "GettingStarted")
It says it still requires 5 parameters not 4.
It is probably something very simple. Any help would be appreciated.
Upvotes: 0
Views: 168
Reputation: 1038850
No, you are not calling your helper correctly. It should be like this:
@Html.ActionImage("Account/Register", "/images/home/gettingstarted.png", "Edit", "GettingStarted")
Html helpers in ASP.NET MVC are nothing more than extension methods
in C# which I invite you to familiarize yourself with before getting into ASP.NET MVC.
Basically in C#, extension methods are invoked on an instance of the class they are extending. In your case that's the HtmlHelper
class. A Razor view has a property called Html
which is of type HtmlHelper
. So you invoke the extension method on it:
@Html.SOME_EXTENSION_METHOD_THAT_IS_BROUGHT_INTO_SCOPE_BY_A_USING_DIRECTIVE(...)
Of course extension methods are nothing more than static methods that you could also invoke like this (it is wrong, please never invoke an extension method like that - it's not what and how extension methods were designed for):
@HtmlHelpers.ActionImage(Html, "Account/Register", "/images/home/gettingstarted.png", "Edit", "GettingStarted")
Notice how I am passing Html
as first argument of the static method. But never use that.
Upvotes: 2