IsPostBack用法

一、IsPostBack 是Page类有一个bool类型的属性,用来判断针对当前Form的请求是第一次还是非第一次,IsPostBack=false时表示是第一次请求,当IsPostBack=true时,表示是非第一次请求。因

为第一次请求的时候会执行Page_Load,在非第一次请求的时候也会执行Page_Load。为什么对同一个Form有多次请求呢?asp.net中引入了服务器端事件,支持服务器端事件的控件,会发出对当前Form的请求,这样在很多情形下我们就需要区别是否是对这个Form的第一次请求。

二、IsPostBack结论

1、对于使用Server.Transfer进行进行迁移时迁移到的页面其IsPostBack=false 每次刷新页面都是第一次加载页面;

2.  Post方式如果Request中没有请求值,即Request.Form =null则IsPostBack=false;Get方式如果Request中没有请求值,即Request.QueryString =null则IsPostBack=false。

namespace Example
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)   //不是回传即第一次加载页面传过来的值为空
            {
                if (Request.QueryString["id"] != null)
                {
                    Response.Write("回传");
                }

                else

                {

                        Response.Write("不是回传");

                 }
            }
        
        }

        protected void button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("WebForm1.aspx?id=3 ");
        }
    }
}

3.使用Response.Redirect方式向自画面迁移时,此时IsPostBack=false

4.发生跨页提交(CrossPagePostBack),当访问PreviousPage属性的时候,对于源Page,IsPostBack=true。发生跨页提交(CrossPagePostBack)时目标页面是IsPostBack=false。

5.使用Server.Execute迁移到的页面其IsPostBack=false。

Server.Execute和Server.Transfer的区别

Server.Execute("another.aspx")和Server.Transfer("another.aspx")区别: 
Execute是从当前页面转移到指定页面,并将执行返回到当前页面 
Transfer是将执行完全转移到指定页面

二、解决编辑数据时数据更新的数据原来的,无法修改的问题

解析:因为当后台编辑数据时,先从后台查询出需要编辑的数据,此时是在不是回传的情况下从数据库查询出数据,当编辑完数据之后,点击提交按钮,提交数据,此时如果没有判断是否回传,会再次查询原来的数据,造成编辑数据没有改变。

namespace Example
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)   //不是回传即第一次加载页面传过来的值为空
            {

            }
            if (Request.QueryString["id"] != null)
            {
                Bind();
            }
            else
            {
                Response.Write("<script>alert('数据发生改变')</script>");
            }
         
        }
        public void Bind()
        {
            Response.Write("数据");
        }
        protected void button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("WebForm1.aspx?id=3 ");
            //Server.Execute("WebForm2.aspx?id=3");
        }

        protected void CesH_Click(object sender, EventArgs e)
        {
            Label1.Text = "测试";
        }
    }
}

原文地址:https://www.cnblogs.com/lykbk/p/lyk19900723_daima7.html