65.9K
CodeProject 正在变化。 阅读更多。
Home

将ViewState移动到页面底部的另一种方法

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2011年4月14日

CPOL
viewsIcon

9698

如果你将ViewState从页面顶部移动到页面底部,你将获得更好的搜索引擎抓取效果。步骤 1:在应用程序的App_code文件夹中创建一个类文件,并将其命名为PageBase.cs。将以下代码复制到类文件中。using System.IO;using...

如果你将ViewState从页面顶部移动到页面底部,你将获得更好的搜索引擎抓取效果。

步骤 1

在应用程序的App_code文件夹中创建一个类文件,并将其命名为PageBase.cs。将以下代码复制到类文件中。
using System.IO;
using System.Web.UI;

namespace WebPageBase
{
    public class PageBase : System.Web.UI.Page
    {
    /// 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.
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        // Obtain the HTML rendered by the instance.
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        base.Render(hw);
        string html = sw.ToString();
        
        // Close the writers we don't need anymore.
        hw.Close();
        sw.Close();

        // Find the viewstate. 
        int start = html.IndexOf(@"<input type=""hidden"" name=""__VIEWSTATE""" );
        // If we find it, then move it.
        if (start > -1)
        {
            int end = html.IndexOf("/>", start) + 2;
            
            string strviewstate = html.Substring(start, end - start);
            html = html.Remove(start, end - start);

            // Find the end of the form and insert it there.
            int formend = html.IndexOf(@"</form>") - 1;
            html = html.Insert(formend, strviewstate);
        }

        // Send the results back into the writer provided.
        writer.Write(html);
    }
}
}

第二步

让你的aspx页面继承自基础类。
public partial class Page : WebPageBase.PageBase
{
	// Your code here
}
© . All rights reserved.