简体   繁体   English

Asp.Net中的IsPostBack和刷新之间的区别

[英]Difference between !IsPostBack and refresh in Asp.Net

I have written some codes in !IsPostBack block. 我已经写了一些代码!IsPostBack块。 This code is getting executed when the page loads for the first time. 第一次加载页面时,将执行此代码。 That is fine. 那样就好。 But the problem is, when I refresh the page by hitting the f5 key this executes again which I don't want to do. 但问题是,当我通过按f5键刷新页面时,这又重新执行,我不想这样做。 I have searched many articles and found difference between PostBack and refresh. 我搜索了很多文章,发现PostBack和刷新之间的区别。 I know about this. 我知道这件事。 But my question is difference between !IsPostBack and Refresh. 但我的问题是!IsPostBack和Refresh之间的区别。 Can we write some code which executes only when the page loads for the 1st time not when we refresh the page. 我们可以编写一些代码,这些代码仅在第一次加载页面时执行,而不是在刷新页面时执行。 By the way I have written my !IsPostBack block inside Page_Init() method and I am using c# for codebehind. 顺便说一句,我在Page_Init()方法中编写了我的!IsPostBack块,我正在使用c#进行代码隐藏。 Thanks. 谢谢。

Refersh and IsPostback are somewhat unrelated: Refersh和IsPostback有点不相关:

  • Refresh in browser generally mean "re-run last action that resulted in this page". 在浏览器中刷新通常意味着“重新运行导致此页面的最后一个操作”。 Usually it causes GET request, but it as well can cause POST if page was shown as result of postback. 通常它会导致GET请求,但如果页面显示为回发的结果,它也会导致POST。 Side note: you often can find sites warning you not to refresh page during non-reversible operations like "charge my credit card" as it may trigger duplicate post. 附注:您经常可以找到警告您不要在不可逆操作期间刷新页面的网站,例如“收取我的信用卡”,因为它可能会触发重复发布。
  • IsPostBack simply states that request come to server as POST, not GET. IsPostBack只是声明请求作为POST来到服务器,而不是GET。

Combining that you can get Refresh that triggers either branch of if (IsPostBack) check. 结合你可以得到刷新触发if (IsPostBack)检查的任一分支。 In most cases so server will receive GET request and hence execute !IsPostBack branch. 在大多数情况下,服务器将接收GET请求,因此执行!IsPostBack分支。

If you really need to detect if page was rendered once already - setting cookie or writing information into Session would be reasonable solution. 如果你真的需要检测页面是否已经呈现过一次 - 设置cookie或将信息写入Session是合理的解决方案。

Please change your code behind code as given below. 请更改代码,如下所示。

        Boolean IsPageRefresh;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["postids"] = System.Guid.NewGuid().ToString();
                Session["postid"] = ViewState["postids"].ToString();
            }
            else
            {
                if (ViewState["postids"].ToString() != Session["postid"].ToString())
                {
                    IsPageRefresh = true;
                }
                Session["postid"] = System.Guid.NewGuid().ToString();
                ViewState["postids"] = Session["postid"].ToString();
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM