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

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...