Baxter
Baxter

Reputation: 5845

Inline C# code vs Page_Load method

I am working on an ASP.NET Web Application.
I have two files -> example.aspx and its code behind example.aspx.cs

I am wondering what the difference is between putting inline C# code at the top of example.aspx

<%    
    if (Session["Page"] != null)
    {    
        //method that maps session vars to form elements
        loadSessionData();
    }        
%>

and putting the code in the Page_Load() method of the code behind file example.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
     if (Session["Page"] != null)
     {    
         //method that maps session vars to form elements
         loadSessionData();
     }  
}

Depending where I put the code the application behaves different in regards to loading the session data into the form elements.

Any help on this would be greatly appreciated.

Update: I figured out why depending on where I put the code the application behaved differently. If I put the inline C# method call at the top of the .aspx it does not run on postbacks. If I put the C# method call in the Page_Load() method of the .aspx.cs code behind file it does run on postbacks. So if I want to put the method in the Page_Load method but not run it on postbacks I would need to wrap it in:

if (!IsPostBack)
{
    loadSessionData();
}

Upvotes: 3

Views: 4732

Answers (2)

Ali Umair
Ali Umair

Reputation: 1424

if you are just asking Inline Coding VS code behind , this is worth checking. ASP.NET - Inline vs. Code-Behind

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30446

I would think the biggest difference would be the moment when the code is executed. Page_Load occurres before the Page_Render which is when (I think) inline code is executed.

Upvotes: 3

Related Questions