3

I have used general Link as rendering parameter . How I can extract URL in c#. For Single line text I am using below piece of code.

 var renderingModel = Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull;
  var topResults = renderingModel.Rendering.ParamValue("TopResults");
1
  • How does your presentation details raw value looks like with that url field? there should be par="..." or s:par="..." in it. What's inside that attribute?
    – Marek Musielak
    May 16, 2019 at 14:43

1 Answer 1

5

If you do not have Glassmapper, OOTB sitecore doesn`t have helpers to cast rendering parameter to link field.

You can retrieve parameter value the same as single-line text, but as a result you will get raw value of link field. It will be look like (depends on link type):

// Internal link
<link text="" anchor="" linktype="internal" class="" title="" target="" querystring="" id="{FCC08AE8-449A-400C-A7CB-0898F7221B2A}" /> 

// Media link
<link linktype="media" target="" id="{4AA4EA35-5AD1-4787-BE62-BDFC890F835D}" />

// External link
<link linktype="external" url="https://google.com" anchor="" target="" />

What you need to do is to parse from xml parameter "id" for internal link or "url" for external (you can also check 'linktype' to determine what type is your link):

var renderingModel = Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull;
var topResults =  renderingModel.Rendering.Parameters["TopResults"];

// Move this code to extention method or helper

var url  = "";
var itemId = Sitecore.Xml.XmlUtil.GetAttribute("id", XmlUtil.LoadXml(topResults));
var linkUrl = Sitecore.Xml.XmlUtil.GetAttribute("url", XmlUtil.LoadXml(topResults));

if (!string.IsNullOrEmpty(linkUrl))
{
    url = linkUrl;
}
else if (itemId != null)
{
    Item urlItem = Sitecore.Context.Database.GetItem(itemId);

    if (urlItem != null) 
    {
        url = Sitecore.Links.LinkManager.GetItemUrl(urlItem);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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