Thursday, August 26, 2010

How to avoid rendering VIEWSTATE, EVENTVALIDATION and other hidden fileds

public class PageBase : Page
{
    string[] tags = { "__VIEWSTATE""__EVENTTARGET""__EVENTARGUMENT""__EVENTVALIDATION" };
    protected override void Render(HtmlTextWriter writer)
    {
        StringBuilder sb = new StringBuilder();
        HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
        base.Render(htw);
        string html = sb.ToString();
        foreach (string tag in tags)
            html = this.RemoveTag(tag, html);
        writer.Write(html);
    }
    public string RemoveTag(string tag, string html)
    {
        int lowerBound = html.IndexOf(tag);
        if (lowerBound < 0) return html;
        while (html[lowerBound--] != '<') ;
        int upperBound = html.IndexOf("/>", lowerBound) + 2;
        html = html.Remove(lowerBound, upperBound - lowerBound);
        if (html.Contains(tag)) html = this.RemoveTag(tag, html);
        return html;
    }
}
public partial class Test : PageBase
{
}

2 comments:

Tom said...

Hi Charith,

Maybe I misunderstand, but it looks line there's a superfluous line here:

while (html[lowerBound--] != '<') ;

Does this do anything?

Thanks!
Tom

Charith Shyam Gunasekara said...

Hello Tom,

This is to decrease 'lowerBound' until it find '<' in the string

Thanks

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...