3

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();
}
1
  • 1
    The <%...%> is run as the page renders....
    – Aristos
    Commented May 2, 2013 at 1:23

2 Answers 2

3

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.