Search code examples
c#asp.nethead

Move code from .aspx file to .cs file without any difference


I have some code in <head> in .apsx I would like to move to my .cs file. So I just move it to my Page_Load(), and it everything would result in the same? Thanks.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
    <%
        var v = new Something(); // Want to move this to .cs
    %>
</head>
</html>

Equal to?

protected void Page_Load(object sender, EventArgs e)
{
    var v = new Something();
}

Solution

  • As mentioned by others, it depends on what your code is doing exactly.

    Your code snippet var v = new Something(); would work exactly the same.

    But, the time at which those 2 pieces of code are executed is much different. Page_Load happens way before any code on the actual aspx page is run. Code on the aspx page itself doesn't run until the Render event I believe. You can look at the Page Lifecycle to see the full list of events.