1

I have a number of places in my code where I render links from templates like so:

<a href="@(Model.Link == null ? string.Empty : Model.Link.Url)">@Model.Link.Text</a>

However I've realized that this leaves off any querystring that is set on the link. I know that I can add this manually by doing href="@(Model.Link == null ? string.Empty : Model.Link.Url + "?" + Model.Link.Query)" but is there a simpler way to just get the full link url and querystring, without having to explicitly include the query everywhere in my code?

2
  • 1
    The method you're looking for is Html.Glass().BeginRenderLink(Model, x => x.Link). Have a look at that and you should see the correct way to do this. – Matthew FitzGerald-Chamberlain Jun 18 '20 at 17:55
  • @Erica, did my answer help? – Paulson Maclean Jun 22 '20 at 12:44
0

This can be achieved easily using Sitecore field helper methods like below :

Just change the anchor tag line from

<a href="@(Model.Link == null ? string.Empty : Model.Link.Url)">@Model.Link.Text</a>

to the format below

@Html.Sitecore().Field(string fieldName/fieldID, Item item)

This will help you to avoid the need to explicitly call the Link's query property everywhere in your code. Also, as far as I know, this is the best solution that reduces the need to write explicit code for adding other attributes such as href, text to the anchor tag. These basic link properties are automatically rendered in your code, if you just supply fieldName and an Item object.

ProTip: If you need to add css classes or any additional attributes to the rendered link tag, just navigate to this helpful link written by Marcotana that I have been using for my reference and slightly tweak the code : https://marcotanainsights.wordpress.com/2017/10/05/tips-on-using-html-sitecore-fields-parameters-object/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.