Raw ActionLink linkText

I want to put the button as the text of @ActionLink() , but I cannot, because the HTML escapes my string ... I found the @Html.Raw() mechanism and tried @ActionLink().ToHtmlString() , but could not figure out how to do this ...

I found an article that describes building an extension for a similar purpose, but is it eeky to go to this big problem ... is there being an easy way?

+8
asp.net-mvc-3 razor html-helper actionlink
source share
2 answers

You could write an assistant:

 public static class HtmlExtensions { public static 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 set the default routes:

 <a class="foo" href="/home/foo/123"><span>Hello World</span></a> 
+13
source share

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

  public static 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())); } 
+1
source share

All Articles