I was looking for the code I once used to put the viewstate tag at the bottom of the form tag, instead of the top. I found some code, used an automated VB-to-C# converter, and the results were not good.
I'm not sure if this is a difference between C# and VB or just a bug posted on Scott's blog, but the insertion place was wrong. So I changed that (removed the -1) and also changed the way he checked if the viewstate object was found, so that if not, we'd still have the original html, before removing the tag.
Edit: I now just saw that someone commented on the -1 issue on that page. Anyway, here's my code:
/// <summary>
/// This method overrides the Render() method for the page and moves the ViewState
/// from its default location at the top of the page to the bottom of the page. This
/// results in better search engine spidering.
/// </summary>
/// <param name="writer"></param>
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
string newHtml = string.Empty;
int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
if ((StartPoint >= 0))
{
// does __VIEWSTATE exist?
int EndPoint = (html.IndexOf("/>", StartPoint) + 2);
string ViewStateInput = html.Substring(StartPoint, (EndPoint - StartPoint));
//I'm using newHtml so that if we cannot find the viewsource's right location, we still have the original html
newHtml = html.Remove(StartPoint, (EndPoint - StartPoint));
int FormEndStart = (newHtml.IndexOf("</form>"));
if ((FormEndStart >= 0))
{
//success - so replace the string, putting the viewstate at the end.
html = newHtml.Insert(FormEndStart, ViewStateInput);
}
}
writer.Write(html);
}
posted @ Friday, June 01, 2007 12:48 PM