Search code examples
sitecoresitecore7html-rendering

Modify sc:Link so that it renders no href but onclick event


I want to modify the sitecore sc:Link control, so that it doesnt render an a tag with href. I want it to call a js function as onClick event.

The page editor functionality should stay the same.

Which class should I override?

I looked at Sitecore.Web.UI.WebControls.Link and LinkProvider, but they dont contain the part which renders the html.


Solution

  • Well I had fun figuring this out - as it happens it's not too complicated.

    First thing I discovered is that Sitecore's Links aren't User Controls, they're Web Controls - which I haven't really worked with before so I don't understand half of what I've just done.

    Internally it looks like Sitecore's FieldControl class just collects together a bunch of attributes inside to render that link element - so we're able to override the PopulateParameters virtual method (ensuring we call the base method to make the default behaviour still happen) and then specify an onclick attribute.

    So this is what the final code of my class looks like.

    [ToolboxData("<{0}:JavascriptLink runat=server></{0}:JavascriptLink>")]
    public class JavascriptLink : Sitecore.Web.UI.WebControls.Link
    {
        protected override void PopulateParameters(SafeDictionary<string> parameters)
        {
            base.PopulateParameters(parameters);
            parameters.Add("onclick", "alert('test')");
        }
    }
    

    You'll then need to register the control slightly differently than you would a User Control - since you mentioned in the comments you need to use it globally you'll probably want to register it in the web.config - I was using this page as a guide