简体   繁体   中英

Page_Load method running twice

I have created a VS 2013 project using built-in asp.net Web Application Web Forms template. By putting a breakpoint in the Page_Load method of a page I can see the method is executed twice between pressing F5 and the page appearing. Why? And can I / should I stop this behaviour?

Apologies for not providing enough detail. The code is completely vanilla, untouched template code generated by VS Exp 2013 for Web.

The ASPX file is

<%@ Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="mycompanyname.B1WebApp.About" %>

The ~/Site.Master has an empty Page_Load method (not sure this is relevant)

The code behind is

public partial class About : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Boolean Nothing;
    }
}

This is part asp.net web forms, as a page posts back to itself whenever a server control is used on a page. It has been like this forever.

You need to do a check on page load:

if(!IsPostBack) 
{  
//Code for first time load 
}
 else 
{ 
// code whenever you have a postback
}

You can avoid pageload function working on each postbacks by !IsPostBack

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Your code here
        }
    }

A User control with this master page can also cause pageload execute twice...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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