Getting ugly with BeginActionLink helper!

Have You ever had such a moment when the most stupid and trivial solution turns out to be the ONLY ONE that is logically suitable at the moment? When I had such a feeling today…. I am working on a module for one of huge web portals (not to mention which one). Part of that module is only accessible to users with administration permissions - as typical as it can be. The reason why I am mentioning that is to highlight the fact that at this specific part performance does not matter so much. Anyway, my talk to one of designers (Friday, half an hour before ‘the beginning of the weekend’): Designer: I am going to spend whole weekend on those Views… Me: Yeah… S*** happens…. Designer: Those ‘Html.ActionLink’ that You use everywhere, how do I put something inside, you know, images, spans, staff like that… Me: Argh… Hm….. I suddenly realize that before I leave the office this guy needs an extension method: BeginActionLink like right now!. The similar one that is used for Forms elements (BeginForm). Then I started to code… Have You ever realized that ActionLink has roughly 12 overloads!!!! That would take hours to prepare BeginActionLink for most of them.

idea bulb

When You are blocked, what You do? Me too, I started ‘googling’. Nothing simple and smart enough. Except 200 lines of code with tons of overloads… argh… But then, completely unexpectedly …. My moment of genius! Don’t laugh! For people over … some age … that things do not happen offen! :) There are solutions that developers are ashamed of, but they simply do their job: public static string TrimEndTag(this MvcHtmlString htmlString, string tagName = “a”) { var endTag = new TagBuilder(tagName).ToString(TagRenderMode.EndTag);

        var tagString = htmlString.ToString();

        var endTagIndex = tagString.LastIndexOf(endTag);

        if(endTagIndex > 0)
            tagString = tagString.Remove(endTagIndex).TrimEnd();

        return tagString;

    public static string ToEndTag(this HtmlHelper html, string tagName)
        return new TagBuilder(tagName).ToString(TagRenderMode.EndTag);

I am simply removing end tag from ActionLink returned string! As simple as that! So all that is left for my buddy to do is to use it like that: <%= Html.ActionLink(” “, “testAction”, “testController”, new { id = 4 }, new {}).TrimEndTag() %>

    images, spans, text, whatever...

<%= Html.ToEndTag("a") %>

Wuala! Ugly, So ugly, but at the same time I am preserving original methods for ActionLinks and I couldn’t figure out better solution….

comments powered by Disqus