Question

I am creating a site with asp.net. I would like to be able to edit the html output of my masterpage, pages and user controls before the output is sent to the user. I have found some functions on the internet that should allow me to edit the code via prerender functions, but none of them seem to work.

I would like to remove the html comments from my code for example. Is it possible to do some regex functions on the html before rendering?

Was it helpful?

Solution

If you simply want to remove comments from code before they are rendered to the client, then change the way you are commenting. Use server-side comments = <%-- hi --%>:

So this:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it -->
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p>
<%-- Don't remove this <p> either because both our clients and our boss are too dumb to figure it out  --%>
<p>Tip 2: Type your last name in the field labeled "Last Name".</p>

Will be rendered as:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it -->
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p>

<p>Tip 2: Type your last name in the field labeled "Last Name".</p>


But, if you actually need to edit output HTML before rendering to the client on a global scale, and you can't just fix it in the code, you could do this in the master page:

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter tw = new HtmlTextWriter(sw);
    base.Render(tw);
    string yourHTML = sw.ToString();
    // do stuff with yourHTML
    writer.Write(yourHTML);
    tw.Dispose();
    sw.Dispose();
}

So in a very simple example, if you have the code

<h1>I'm a big fat h1</h1>

you could in that function have:

yourHTML = yourHTML.Replace("<h1>","<h5>");
yourHTML = yourHTML.Replace("</h1>", "</h5>");

So now that above code is rendered as

<h5>I'm a big fat h1</h5>

To fulfill the very legit requirement to change all h1 tags to h5 before they are rendered to browser.

OTHER TIPS

I think what you're looking for is ControlAdapters

I have used them before with SharePoint to all me to make the output code more accessible. You register them in the WebConfig then the rendered controls are passed through. At this point, you can use a regext to process and amend the emmited markup

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top