2014-01-23

Using an ActionLink in a MVC Razor Declarative Helper

I have a declarative MVC Razor helper. I want to include an ActionLink inside it. This is currently a limitation on Razor helpers that you can't nest them. They keep promising to make it work in the "next version," but so far it isn't there.

So this doesn't work:

@helper DoesntWork(string text)
{
 @Html.ActionLink(text, "Index", "Bar")
}

The way around it takes advantage of the fact that ActionLink is merely a static method inside an extension class. You need to reference the actual method, and pass the html context as the first argument.

@helper Works(string text)
{
  @System.Web.Mvc.Html.LinkExtensions.ActionLink(

      ((System.Web.Mvc.WebViewPage)CurrentPage).Html, text, "Index", "Bar")
}

You should know that an extension method is just syntatic sugar that allows you to use Html.ActionLink("foo") instead ActionLink(Html, "foo"). So if you can't use an it as an extension method, you can always fall back to just using it as a static method, if you can pass in the right first argument.

No comments :

Post a Comment