Monday, February 21, 2011

Edit Html.ActionLink output string

I'm trying to output the following HTML using Html.ActionLink:

<a href="/About" class="read-more">Read More<span class="arrow">→</span></a>

I'm getting it done by doing an ActionLink, which outputs an <a> tag and then manipulating the string.

<%= Html.ActionLink("[[replace]]", "Index", "About", null, new { @class = "read-more" }).ToHtmlString().Replace("[[replace]]", "Read More" + "<span class='arrow'>→</span>")%></p>

It'd be good if I could put HTML directly into the ActionLink but there doesn't seem to be a way based on my internet searches. Sure, it works but it seems like a hack. Is there a better way to accomplish this?

From stackoverflow
  • You could write you're own HTML helper class and make it fit whatever needs you have. I've wrote a few before, I see the ones you get with MVC as just a start.

    Here's a link with a tutorial. And here's and official MS video on how to.

  • If all you need is the arrow and you could use an image, you could use stylesheet to put that image after the link

    .readmore-link{background-image: url('/image.png'); padding-right: 16px; /*...*/}
    

    just tweak the image position etc.

    Otherwise I'd recommend writing extension method for HtmlHelper.

  • Aaron...Did you work this out?

    I use Url.Action in the href attribute when I need something other than just the link text in the outputted HTML.

    <a href="<%= Url.Action("About") %>" class="read-more">Read More<span class="arrow">→</span></a>
    

    Hope this helps.

    Cheers, -jc

0 comments:

Post a Comment