Alex Rivera | Logout

How to use ASP.NET MVC Html Helpers from a custom helper?

Asked 2009-05-18T07:58:51.120
12

I have several pages listing search results, for each result I would like to display I want to create a custom View Helper in order to avoid duplicating the display code.

How do I access the convenient existing view helpers from my custom view helper? I.e. in my custom view helper I would like to use Url.Action(), Html.ActionLink, etc. How do I access them from my custom view helper?

using System;
namespace MvcApp.Helpers
{
    public class SearchResultHelper
    {
        public static string Show(Result result)
        {
            string str = "";

            // producing HTML for search result here

            // instead of writing
            str += String.Format("<a href=\"/showresult/{0}\">{1}</a>", result.id, result.title);
            // I would like to use Url.Action, Html.ActionLink, etc. How?

            return str;
        }
    }
}

using System.Web.Mvc gives access to HtmlHelpers, but non of the convenient methods like ActionLink seem to be present.

Edit
Report

1 Answer

9

This example should help you. This helper renders different link text depending on whether the user is logged in or not. It demonstrates the use of ActionLink inside my custom helper:

    public static string FooterEditLink(this HtmlHelper helper,
        System.Security.Principal.IIdentity user, string loginText, string logoutText)
    {
        if (user.IsAuthenticated)
            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, logoutText, "Logout", "Account",
                new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
        else
            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, loginText, "Login", "Account",
                new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
    }

EDIT:
All you would need to do to to access the Url.Action() method would be to replace the this HtmlHelper helper param with something like this UrlHelper urlHelp and then just call urlHelp.Action(...

Hope this helps.

answered 2009-05-18T08:03:06.900

Your Answer