radbyx
radbyx

Reputation: 9670

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();
}

Upvotes: 3

Views: 242

Answers (6)

giri77
giri77

Reputation: 71

it depends where you want to move the logic - on page load or on any event fire.

Upvotes: 1

yapingchen
yapingchen

Reputation: 866

<% %> run in the client render

the protected void Page_Load(object sender, EventArgs e) { var v = new Something(); } run the server page lifecycle

so you can see the article (msdn) http://msdn.microsoft.com/en-us/library/ms178135(v=vs.80).aspx

Upvotes: 0

Matthew
Matthew

Reputation: 25773

protected Something v;

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

That is closer to what you have, this way you can actually still use the variable in the aspx page.

Upvotes: 1

Doozer Blake
Doozer Blake

Reputation: 7797

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.

Upvotes: 2

manny
manny

Reputation: 1948

yes, or you can inherit to other name

Upvotes: 0

mamoo
mamoo

Reputation: 8166

It depends on the scope in which you want to use v. If you want to make it available through all the page just declare it as a class member.

Upvotes: 2

Related Questions