CodeFile vs CodeBehind

asp.net

asp.net Problem Overview


What is the difference between CodeFile="file.ascx.cs" and CodeBehind="file.ascx.cs" in the declaration of a ASP.NET user control?

Is one newer or recommended? Or do they have specific usage?

asp.net Solutions


Solution 1 - asp.net

CodeBehind: Needs to be compiled (ASP.NET 1.1 model). The compiled binary is placed in the bin folder of the website. You need to do a compile in Visual Studio before you deploy. It's a good model when you don't want the source code to be viewable as plain text. For example when delivering to a customer to whom you don't have an obligation to provide code.

CodeFile: You provide the source file with the solution for deployment. ASP.NET 2.0 runtime compiles the code when needed. The compiled files are at Microsoft.NET[.NET version]\Temporary ASP.NET Files.

Solution 2 - asp.net

I'm working with an Application Project in Visual Studio Express 2012 For Web and using .NET 4.0. In the code behind files for my login and change password pages I found a situation where I needed both CodeBehind and CodeFile in the declaration.

If I don't add a code file reference like

CodeFile=login.aspx.cs

The web page doesn't parse and the browser displays a parser error. It doesn't matter whether I compile the project or not.

If I don't add a code behind reference like

CodeBehind=login.aspx.cs

References to Security classes like MembershipUser fail both at compile time and when attempting to use intellisense with an error like "The type or namespace MembershipUser cannot be found". I have added a reference to System.Web.ApplicationServices as required by the .Net 4.0 framework.

I should add that these troublesome files are running in an application within the website created using the IIS Application tool. When I open the website from Visual Studio I have no difficulty with parser errors or reference errors. This confusion only occurs when I open the application as a project in Visual Studio.

Solution 3 - asp.net

Codebehind file need to compile before run but in src we dont need to compile and then run.. just save the file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoldarnalView Question on Stackoverflow
Solution 1 - asp.netShafqat AhmedView Answer on Stackoverflow
Solution 2 - asp.netDavidHyogoView Answer on Stackoverflow
Solution 3 - asp.netRanjeet PrasadView Answer on Stackoverflow