Stefan Says

Opinions on ASP.NET, ASP, databases etc
posts - 32, comments - 25, trackbacks - 23

Code in ASPX-files or codebehind?

As you might know there are two ways of writing code in ASP.NET - you can either use the codebehind approach

<%@ Page Language="C#" CodeFile="YourPage.aspx.cs" 
    Inherits="YourPage" AutoEventWireup="true" %>

where the ASPX file so to speak inherits from a class in a vb/cs file.

Or you can insert your code inside the ASPX file like this:

<%@ Page Language="C#" %>
<script runat="server">
void YourButton_Click(Object sender, EventArgs e)
{
   //run your code
}
</script>

So what is better? Well simply put I use codebehind almost all the time. Why? Better performance? No, one might think so, but performance has nothing to do with it - in fact it is equal. Just-in-time compilation of the ASPX file with code inside it will make it look and perform just the same as the compiled codebehind solution.

So what's the difference if performance is not it?

One is that with code behind you have some protection of your code. While decompiling a dll might not be too hard it Reflector or Anakrino at least it isn't available for anyome. If you use DLL:s  you have the possibility to use an obfuscator which makes it even harder to recompile your code.

On the other hand - the "single file solution" enables really easy changes. No recompilation and uploading of a new dll file needed. Maybe you are on the road with no access to your Visual Studio. Just make the change and it's there.

But the biggest thing is structure. GUI is GUI and code is code. That should be enough.

However there are times I use the singlepage model, say when you just need to add a single simple page to a certain place on your website - I sometimes use it for default.aspx 301 redirections for example on my site. Just put up a page, add a few lines:

<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.aspcode.net/articles/l_en-US/t_default/Projects/Sendmail-(ASP)/category_11.aspx");
}
</script>

 

  

 

Print | posted on Friday, September 15, 2006 2:11 PM