📜 ⬆️ ⬇️

Move ViewState to the bottom of the page.

Problem


We continue the fight against ViewState when using WebForms (the use of this technology is determined by the party’s policy using the WCSF pattern in the company's projects).

In the previous article, I considered the possibility of transferring the ViewState from the user's browser to the session. It's great that we managed to get rid of the ViewState on the page, but this method can sometimes cause the problem of restarting the state server (although my more experienced comrades have not encountered it).

If, after all, you decide to leave ViewState on the side of the browser, another problem arises (besides bloated html) - all other things being equal, search engines rank information better if it is contained closer to the top of the page. Naturally, the presence of a huge ViewState at the beginning of each page is undesirable.

')

Decision


So, all we need is to intercept the output stream, cut a hidden field from the beginning of the page with ViewState and insert it before the closing tag of the form.
Write the page adapter :
using System.IO;
using System.Web.UI;

namespace MyCompany.Web
{
/// <summary>
/// ViewState
/// </summary>
public class MoveViewStatePageAdapter : System.Web.UI.Adapters.PageAdapter
{
protected override void Render(HtmlTextWriter writer)
{
// HTML,
var sw = new StringWriter ();
var hw = new HtmlTextWriter(sw);

base .Render(hw);
var html = sw.ToString();

hw.Close();
sw.Close();

// ViewState
var start = html.IndexOf( @"<input type=" "hidden" " name=" "__VIEWSTATE" "" );

if (start > -1)
{
var end = html.IndexOf( "/>" , start) + 2;

// ViewState
var viewstate = html.Substring(start, end - start);
html = html.Remove(start, end - start);

// ViewState
var formend = html.IndexOf( "</form>" ) - 1;
html = html.Insert(formend, viewstate);
}

// HTML
writer.Write(html);
}
}
}

* This source code was highlighted with Source Code Highlighter .


In the folder App_Browsers create the file default.browser with the contents:
< browsers >
< browser refID ="Default" >
< controlAdapters >
< adapter controlType ="System.Web.UI.Page" adapterType ="MyCompany.Web.MoveViewStatePageAdapter" />
</ controlAdapters >
</ browser >
</ browsers >


* This source code was highlighted with Source Code Highlighter .


See the result!

PS Code used from Moving View State to the Bottom of the Page
Another solution using the http module.

Source: https://habr.com/ru/post/77187/


All Articles