Here are two code snippets to help you make a XhtmlString display external links instead of the internal ones and also render blocks, dynamic content etc. This could be helpful if you don’t have access to a HtmlHelper like in a WebApi.
The first one just converts links. It loops through all fragments and converts internal UrlFragments to external.
1 2 3 4 5 6 7 8 9 10 11 |
public static XhtmlString ToExternalLinks(this XhtmlString xhtmlString) { var result = new StringBuilder(); foreach (var fragment in xhtmlString.Fragments) { var urlFragment = fragment as UrlFragment; result.Append(urlFragment != null ? UrlResolver.Current.GetUrl(new UrlBuilder(urlFragment.InternalFormat), ContextMode.Default) : fragment.InternalFormat); } return new XhtmlString(result.ToString()); } |
Next snippet will also render blocks, dynamic content etc. It creates a “fake” HtmlHelper and then uses the same method as within EPiServer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public static string ConvertToExternal(this XhtmlString xhtmlstring) { if (string.IsNullOrWhiteSpace(xhtmlstring?.ToHtmlString()) || xhtmlstring.IsEmpty) { return string.Empty; } var routeData = new RouteData(); routeData.Values.Add("controller", "a"); routeData.Values.Add("subject", "a"); var hh = new HtmlHelper(new ViewContext() { HttpContext = new HttpContextWrapper(HttpContext.Current), ViewData = new ViewDataDictionary(), TempData = new TempDataDictionary(), Controller = new DummyController(), RouteData = routeData }, new ViewPage()); string result; using (var writer = new StringWriter()) { hh.ViewContext.Writer = writer; hh.RenderXhtmlString(xhtmlstring); writer.Flush(); result = writer.ToString(); } return result; } |