0

I have a razor page that I am building using content that has been saved in a database. As this content is from a wysiwyg, I convert it to a MvcHtmlString and then display it on my page.

ContentPageModel.Content = MvcHtmlString.Create(contentFromDb);

However, the editor we use preppends tildes to the links:

<p>Some text around a link <a href="~/contact">Contact Us<a></p>

And when I render the string in the view, it is not replacing the tilde - I just get the href output as is.

@Model.Content // renders as above without the tilde being converted

Is there a way to convert the tilde to the app path?

Pete
  • 57,112
  • 28
  • 117
  • 166

1 Answers1

0

In the end I have made a converter in my auto mapper so that it would resolve the urls when converting strings to an MvcHtmlString (with the help of html agility pack)

public sealed class MvcHtmlStringConverter : ITypeConverter<string, MvcHtmlString>
{
    public MvcHtmlString Convert(string source, MvcHtmlString destination, ResolutionContext context)
    {
        if (!string.IsNullOrWhiteSpace(source))
        {
            if (source.IndexOf("~") > -1)
            {
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(source);

                CleanAttributes(document.DocumentNode.SelectNodes("//img[starts-with(@src, '~')]"), "src");
                CleanAttributes(document.DocumentNode.SelectNodes("//a[starts-with(@href, '~')]"), "href");

                destination = MvcHtmlString.Create(document.DocumentNode.OuterHtml);
            }
            else
            {
                destination = MvcHtmlString.Create(source);
            }
        }
        else
        {
            destination = MvcHtmlString.Empty;
        }

        return destination;
    }

    private static void CleanAttributes(HtmlNodeCollection htmlNodeCollection, string attribute)
    {
        if (htmlNodeCollection != null && htmlNodeCollection.Count > 0)
        {
            foreach (HtmlNode node in htmlNodeCollection)
            {
                string attributeValue = node.Attributes[attribute].Value;

                if (attributeValue.StartsWith("~"))
                {
                    node.SetAttributeValue(attribute, VirtualPathUtility.ToAbsolute(attributeValue.ToLower()));
                }
            }
        }
    }
}

Which I use as described in this answer

Pete
  • 57,112
  • 28
  • 117
  • 166