Anders Hattestad
Feb 11, 2014
  18947
(1 votes)

How to get html from a view and change the content in MVC

There are times you want to manipulate the html after it has created to change image references, or change the links outputted to friendly URL’s. Here is a trick how to get the content out of a view in MVC and use the HtmlAgilityPack to change the content.

If you have a view you want to render, for instance in the _Layout.cshtml and you want to change html you could have lines like this:

    @Html.PropertyForWithChangeHtml(p => p.StartPage.Row1)
    @Html.RenderViewWithChange("~/Views/MasterPages/HtmlFooter.cshtml", Model)

The extension code that will render the PropertyFor is like this:

public static MvcHtmlString PropertyForWithChangeHtml<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    return PropertyForWithChangeHtml(html, expression, null);
}
public static MvcHtmlString PropertyForWithChangeHtml<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData)
{
    var result = html.PropertyFor(expression, additionalViewData);
    var htmlTxt = result.ToString();
    var htmlTxtChanged = ChangeHtml(htmlTxt);
    return new MvcHtmlString(htmlTxtChanged);
}

And the code that will render a view is like this

public static MvcHtmlString RenderViewWithChange(this HtmlHelper html, string viewName, object model)
{
    var htmlTxt = RenderViewToString(html.ViewContext, viewName, model);
    var htmlTxtChanged = ChangeHtml(htmlTxt);
    return new MvcHtmlString(htmlTxtChanged);
}
public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = context.RouteData.GetRequiredString("action");

    ViewDataDictionary viewData = new ViewDataDictionary(model);

    using (var sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        ViewContext viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);

        return ChangeHtml(sw.GetStringBuilder().ToString());
    }
}

The actully changing of the html is easy with the HtmlAgilityPack. This code will ensure that all links are friendly EPiServer URL's

public static string ChangeHtml(string html)
{
        var doc = new HtmlDocument();
        doc.LoadHtml(html);
        FiksNodes(doc.DocumentNode);
        return doc.DocumentNode.OuterHtml;
}

public static void FiksNodes(HtmlNode node)
{
    if (node.Attributes.Contains("href"))
    {
        var val = node.Attributes["href"].Value;
        ChangeLinkToFriendly(node, val, "href");
    }
    if (node.Name == "form" && node.Attributes.Contains("action"))
    {
        var val = node.Attributes["action"].Value;
        ChangeLinkToFriendly(node, val, "action");
    }
    for (int i = 0; i < node.ChildNodes.Count; i++)
    {
        FiksNodes(node.ChildNodes[i]);
    }
}
private static void ChangeLinkToFriendly(HtmlNode node, string val, string key)
{
    if (val.StartsWith("/link/"))
    {
        var decoded = HttpUtility.HtmlDecode(val);
        var url = new UrlBuilder(decoded);
        PageReference pageRef = null;
        if (url.QueryCollection["id"] != null && PageReference.TryParse(url.QueryCollection["id"], out pageRef))
        {
            EPiServer.Global.UrlRewriteProvider.ConvertToExternal(url, pageRef, System.Text.UTF8Encoding.UTF8);
            node.Attributes[key].Value = url.Uri.IsAbsoluteUri ? url.Uri.AbsoluteUri : url.Uri.OriginalString;
        }
        else
        {
            EPiServer.Global.UrlRewriteProvider.ConvertToExternal(url, null, System.Text.UTF8Encoding.UTF8);
            node.Attributes[key].Value = url.Uri.IsAbsoluteUri ? url.Uri.AbsoluteUri : url.Uri.OriginalString;
        }
        node.Attributes.Add("data-changed-" + key + "-from", val);
    }
}
Feb 11, 2014

Comments

Arve Systad
Arve Systad Feb 11, 2014 10:22 AM

But why write your markup in a way that makes you need to change it afterwards?

And adding the "data-changed" attributse also makes dirty markup.

Anders Hattestad
Anders Hattestad Feb 11, 2014 10:25 AM

It's just an example :)
If you need to change all img tags inside a XhtmlString property, this is a way of doing it.
It could be to Ensure alt tags, or to make the images responsive.

May 21, 2015 10:34 AM

Hi In this case what will be the return type of Action Result..?

Can you please help me i need help regarding same i have same problem..

May 21, 2015 10:36 AM

Actuallly then MOdel validation is not working for me have you any idea that how to do model validation in above approach.

Please login to comment.
Latest blogs
Opti ID overview

Opti ID allows you to log in once and switch between Optimizely products using Okta, Entra ID, or a local account. You can also manage all your use...

K Khan | Jul 26, 2024

Getting Started with Optimizely SaaS using Next.js Starter App - Extend a component - Part 3

This is the final part of our Optimizely SaaS CMS proof-of-concept (POC) blog series. In this post, we'll dive into extending a component within th...

Raghavendra Murthy | Jul 23, 2024 | Syndicated blog

Optimizely Graph – Faceting with Geta Categories

Overview As Optimizely Graph (and Content Cloud SaaS) makes its global debut, it is known that there are going to be some bugs and quirks. One of t...

Eric Markson | Jul 22, 2024 | Syndicated blog

Integration Bynder (DAM) with Optimizely

Bynder is a comprehensive digital asset management (DAM) platform that enables businesses to efficiently manage, store, organize, and share their...

Sanjay Kumar | Jul 22, 2024

Frontend Hosting for SaaS CMS Solutions

Introduction Now that CMS SaaS Core has gone into general availability, it is a good time to start discussing where to host the head. SaaS Core is...

Minesh Shah (Netcel) | Jul 20, 2024

Optimizely London Dev Meetup 11th July 2024

On 11th July 2024 in London Niteco and Netcel along with Optimizely ran the London Developer meetup. There was an great agenda of talks that we put...

Scott Reed | Jul 19, 2024