Resolving links in XhtmlStrings, EPiServer 7.16.1

Did you ever try to store a XhtmlString in a variable and use it in your code? Maybe you noticed that some stuff, like links, isn’t very useful because they are internal.

I noticed this when i upgraded a site from CMS6, and on that site i had a working code that rendered dynamic content so the code i passed to my variable actually was useful, but it broke when i upgraded the site. What i did find than, was that XhtmlStrings are made up of Fragments. And that’s really useful!

One thing you can do with these fragments is resolving internal links, and this is because links are stored as a UrlFragment. A typical XhtmlString could look like:

As you can see, we have regular content, UrlFragments and a ContentFragment. So now, we can write some code to do stuff with different fragements:

Maybe you would like to do something with a block?

Or, if you would like to resolve links in your XhtmlString:

The complete code i use to resolve links before passing the content to a javascript:

 

6 thoughts on “Resolving links in XhtmlStrings, EPiServer 7.16.1

  1. Thanks for sharing!

    You could improve your type checking by just using ‘as’ and then null check:

    var uFragment = sFragment as UrlFragment;
    if (uFragment != null)
    {
    }

    Now you’re only casting the object once, and not three times as in your original code. Way cleaner if you ask me 🙂

    I would also recommend using the UrlResolver instead of the UrlRewriteProvider.

    1. You are absolutely right about the casts. I better update the code before some one use it in a “copy/paste-solution” 🙂

  2. Thank you, it helped me a lot. Just one thing: you forgot to filter fragments: xhtml.Fragments.GetFilteredFragments(_principalAccessor.Principal); (where _principalAccessor is an injected IPrincipalAccessor)

    1. also I’m trying to check if url fragment is internal link by:
      if (urlFragment != null && urlFragment.ReferencedPermanentLinkIds.Count > 0)

Leave a Reply

Your email address will not be published. Required fields are marked *