[歷史]Asp.net 保持頁面提交前窗體位置的類

 

.Net子类

  • NetSubClass:ASP.Net

在Asp.net编程的时候,经常会遇见这样的问题,比如:在一个DataGrid里编辑数据,DataGrid数据显示

很长,我们用鼠标把页面拉到下面进行编辑,编辑好数据提交后,页面又会滚动到最顶端,我们需要再

次滚动页面,找到刚才编辑的数据,好麻烦!现在简单了,定义一个ScrollPage类,把我们的

asp.net 页面的继承类修改为继承ScrollPage就OK了!简单吧!


using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;


namespace ScrollTemplate
{
 public class TemplateScrollPage : System.Web.UI.Page
 {

  public TemplateScrollPage()
  {

  }
  private bool m_UseScrollPersistence = true;
  private string m_BodyID;
  private string saveScrollPosition = "<script language='javascript'>function saveScrollPosition() {{document.forms[0].__SCROLLPOS.value = {0}.scrollTop;}}{0}.onscroll=saveScrollPosition;</script>";
  private string setScrollPosition = "<script language='javascript'>function setScrollPosition() {{{0}.scrollTop =\"{1}\";}}{0}.onload=setScrollPosition;</script>";

  public bool UseScrollPersistence
  {
   get
   {
    return m_UseScrollPersistence;
   }
   set
   {
    m_UseScrollPersistence = value;
   }
  }

  public string BodyID
  {
   get
   {
    return m_BodyID;
   }
   set
   {
    m_BodyID = value;
   }
  }

  protected override void OnPreRender(EventArgs e)
  {
   if (UseScrollPersistence)
   {
    RetainScrollPosition();
   }
   base.OnPreRender(e);
  }

  protected override void Render(HtmlTextWriter writer)
  {
   if ((UseScrollPersistence))
   {
    TextWriter tempWriter = new StringWriter();
    base.Render(new HtmlTextWriter(tempWriter));
    if ((BodyID == null))
    {
     writer.Write(Regex.Replace(tempWriter.ToString(), "<body", "<body id=\"thebody\" ", RegexOptions.IgnoreCase));
    }
    else
    {
     writer.Write(Regex.Replace(tempWriter.ToString(), "<body", "<body id=\" + m_BodyID + \"", RegexOptions.IgnoreCase));
    }
   }
   else
   {
    base.Render(writer);
   }
  }

  private void RetainScrollPosition()
  {
   this.Page.RegisterHiddenField("__SCROLLPOS", "0");
   string s_bodyID;
   if (BodyID == null)
   {
    s_bodyID = "thebody";
   }
   else
   {
    s_bodyID = BodyID;
   }
   RegisterStartupScript("saveScroll", string.Format(saveScrollPosition, s_bodyID));
   if ((Page.IsPostBack))
   {
    RegisterStartupScript("setScroll", string.Format(setScrollPosition, s_bodyID, Request.Form["__SCROLLPOS"]));
   }
  }
 }
}

原文地址:https://www.cnblogs.com/godwar/p/1264910.html