Skip to content Skip to sidebar Skip to footer

Raw Actionlink Linktext

I want to put a button as the text of an @ActionLink() but I can't because it HTML-escapes my string... I found the @Html.Raw() mechanism and have tried the @ActionLink().ToHtmlStr

Solution 1:

You could write a helper:

publicstaticclassHtmlExtensions
{
    publicstatic IHtmlString MyActionLink(this HtmlHelper htmlHelper, 
        string linkText, 
        string action, 
        string controller,
        object routeValues,
        object htmlAttributes
    )
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var anchor = new TagBuilder("a");
        anchor.InnerHtml = linkText;
        anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
        anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        return MvcHtmlString.Create(anchor.ToString());
    }
}

and then use this helper:

@Html.MyActionLink(
    "<span>Hello World</span>", 
    "foo", 
    "home",
    new { id = "123" },
    new { @class = "foo" }
)

which given default routes would produce:

<aclass="foo"href="/home/foo/123"><span>Hello World</span></a>

Solution 2:

If you want to create a custom action link that uses T4MVC library, You can write the below code:

publicstatic System.Web.IHtmlString DtxActionLink(this System.Web.Mvc.HtmlHelper html, string linkText,
        System.Web.Mvc.ActionResult actionResult = null,
        object htmlAttributes = null)
    {
        System.Web.Mvc.IT4MVCActionResult oT4MVCActionResult =
            actionResult as System.Web.Mvc.IT4MVCActionResult;

        if (oT4MVCActionResult == null)
        {
            return (null);
        }

        System.Web.Mvc.UrlHelper oUrlHelper =
            new System.Web.Mvc.UrlHelper(html.ViewContext.RequestContext);

        System.Web.Mvc.TagBuilder oTagBuilder =
            new System.Web.Mvc.TagBuilder("a");

        oTagBuilder.InnerHtml = linkText;

        oTagBuilder.AddCssClass("btn btn-default");

        oTagBuilder.Attributes["href"] = oUrlHelper.Action
            (oT4MVCActionResult.Action,
            oT4MVCActionResult.Controller,
            oT4MVCActionResult.RouteValueDictionary);

        oTagBuilder.MergeAttributes
            (new System.Web.Routing.RouteValueDictionary(htmlAttributes));

        return (html.Raw(oTagBuilder.ToString()));
    }

Post a Comment for "Raw Actionlink Linktext"