Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Another way to moving ViewState to the bottom of page

4.75/5 (4 votes)
19 Apr 2010CPOL 1  
On the Web there are many examples for moving ViewState to the bottom of Page using RegularExpressions. This is another way using HtmlTextWriter.All you nees that add in your project class named MoveViewStateHtmlTextWriter and write in your BasePage code below.protected override...
On the Web there are many examples for moving ViewState to the bottom of Page using RegularExpressions. This is another way using HtmlTextWriter.

All you nees that add in your project class named MoveViewStateHtmlTextWriter and write in your BasePage code below.

protected override HtmlTextWriter CreateHtmlTextWriter(System.IO.TextWriter tw)
{
    return new MoveViewStateHtmlTextWriter(base.CreateHtmlTextWriter(tw));
}


this is source of class MoveViewStateHtmlTextWriter

public class MoveViewStateHtmlTextWriter : HtmlTextWriter
{
	enum State
	{
		None,
		WaitingKeyword,
		WaitingEnd,
		WaitingFormEnd,
		Finished
	}

	State _state = State.None;
	string lastString = null;
	StringBuilder _sb = new StringBuilder();

	public MoveViewStateHtmlTextWriter(TextWriter inner) : base(inner)
	{
	}

	#region Overrides

	public override void Write(string s)
	{
		if (_state != State.WaitingFormEnd && _state != State.Finished)
		{
			if (_state == State.None)
			{
				// may be ViewState
				if (s == "\r\n<input type=\"hidden\" name=\"")
				{
					lastString = s;
					_state = State.WaitingKeyword;
					return;
				}
				// may be ViewState
				else if (s == "<input type=\"hidden\" name=\"")
				{
					lastString = s;
					_state = State.WaitingKeyword;
					return;
				}
			}
			else if (_state == State.WaitingKeyword)
			{
				if (s == "__VIEWSTATE")
				{
					_sb.Append(lastString);
					lastString = null;
					_sb.Append(s);
					_state = State.WaitingEnd;
					return;
				}
				else
				{
					_state = State.None;
					base.Write(lastString);
					lastString = null;
				}
			}
			else if (_state == State.WaitingEnd)
			{
				_sb.Append(s);
				return;
			}
		}
		base.Write(s);
	}

	public override void WriteLine(string s)
	{
		if (_state == State.WaitingEnd)
		{
			_sb.Append(s);
			if (s == "\" value=\"\" />" || s == "\" />")
			{
				_state = State.WaitingFormEnd;
			}
			return;
		}
		if (lastString != null)
			base.WriteLine(lastString);
		base.WriteLine(s);
	}

	public override void WriteEndTag(string tagName)
	{
		if (_state == State.WaitingFormEnd)
		{
			if (tagName == "form")
			{
				base.Write(_sb.ToString());
				_sb.Remove(0, _sb.Length);
				_state = State.Finished;
			}
		}
		if (lastString != null)
			base.WriteLine(lastString);
		base.WriteEndTag(tagName);
	}

	#endregion
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)