|
Introduction
Well, to start, I used a lot of Quotes from MSDN. I think they can explain things better than me, so let's start.
Although Microsoft® Visual Studio® .NET makes it easy to create and work with Web Forms pages using the ASP.NET code-behind model, you might find yourself working with single-file Web Forms pages by circumstance or by preference. This article gives an overview of the differences between the two models, describes how to work with single-file Web Forms pages in Visual Studio, and shows you how to convert single-file .aspx pages to code-behind Web Forms pages.
There are a few differences in the processing of code-behind and single-file pages.
| Code Behind |
Single File |
| The HTML and controls are in the .aspx file, and the code is in a separate .aspx.vb or .aspx.cs file. |
The code is in <script> blocks in the same .aspx file that contains the HTML and controls. |
| The code for the page is compiled into a separate class from which the .aspx file derives. |
The .aspx file derives from the Page class. |
| All project class files (without the .aspx file itself) are compiled into a .dll file, which is deployed to the server without any source code. When a request for the page is received, then an instance of the project .dll file is created and executed. |
When the page is deployed, the source code is deployed along with the Web Forms page, because it is physically in the .aspx file. However, you do not see the code, only the results are rendered when the page runs. |
[Quote MSDN: Working with Single-File Web Forms Pages in Visual Studio .NET]
Using the code
My personal preference is Code Behind. Most free ASP.NET hosting servers don’t allow Code Behind, not sure why, yet.
What I sometimes do is I write a base class, which derives from Page class, and all my pages derive from my base class. But on a Single File Web Form, it derives from the Page class. So, this limits you to create your own base derived class.
Let's start off with a simple app that uses Code Behind and convert that into Single File.
- Open an existing project, or create a new ASP.NET Web application.
- On the Project menu, click Add HTML Page.
- Name the new page with the .aspx extension, for example, SingleForm1.aspx.
- Design the form.
- When your form works in code behind now, we can move it to a Single File.
- Change your design view to HTML.
- Replace your
Page directive with: <%@ Page language="c#" %>
- Between the
<Head></Head> tags, add the following code: <Head>
<script language="CS" runat="server"></script>
</Head>
- Copy and paste your Code Behind code in between the
<script> tags.
Note that I don't have any private / public / ... modifier. <Head>
<script language="CS" runat="server">
void Page_Load(object sender, System.EventArgs e)
{
}
void btnLogon_Click(object sender, System.EventArgs e)
{
this.txtUserID.Text = "Logon";
this.txtPassword.Text = "";
}
</script>
</Head>
- Now. we need to “Register” the event. Due to the fact the I could find the
InitializeComponent method, I registered my events in the Page_Load.
<Head>
<script language="CS" runat="server">
void Page_Load(object sender, System.EventArgs e)
{
this.btnLogon.Click +=
new System.EventHandler(this.btnLogon_Click);
}
void btnLogon_Click(object sender, System.EventArgs e)
{
this.txtUserID.Text = "Logon";
this.txtPassword.Text = "";
}
</script>
</Head>
- There we go.
Now how do I use classes in inline code???
- Well to start off, you can create a .cs file where your class code is declared.
- Between the
<Head></Head> tags, add the following code: <Head>
<script language="cs" runat="server" src= "MySource.cs"/>
<script language="CS" runat="server"></script>
</Head>
- Note that in your source file, you don’t include the namespace. You only declare the class:
public class MyClass1 { }
public class MyClass2
{
protected int Index = 0;
public MyClass2()
{
}
}
public class MyClass3 : System.Collections.CollectionBase
{
public int this[int Index]
{
get
{
return (int)List[Index];
}
set
{
List[Index] = value;
}
}
}
- And you use it the same as what you would have in code behind.
<Head>
<script language="CS" runat="server">
void Page_Load(object sender, System.EventArgs e)
{
this.btnLogon.Click +=
new System.EventHandler(this.btnLogon_Click);
MyClass3 class3 = new MyClass3();
class[0] = "Test";
}
void btnLogon_Click(object sender, System.EventArgs e)
{
this.txtUserID.Text = "Logon";
this.txtPassword.Text = "";
}
</script>
</Head>
| You must Sign In to use this message board. |
|
| | Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh) | FirstPrevNext |
|
 |
|
|
Hello!
I am very new to .NET so if this Q is trivial PLS forgive me. I would like to find some tool to convert inline to codebehind and vs I am learning the hard way and some examples are inline and some are codebehind. This does not make my life any easier 
And WHY cant I just copy the inline code to a codebehind?
Jonas
I have always done things thew hard way...
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi Sorry For Replying now I actually wrote a reply but it seems not to be posted.
What I think the problem is. Is that you aren’t including the event handler And that’s why if you copy your inline code you don’t get the event executed. What you can do is. In you onload event to initialize the event handler for what you are about to call. Example. You got a button on you page and you want to call it. You will need to create the onclick event. MyButton.Click += new EventHandler(MyButton_ClicK)
Hope this helps
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello, I am trying to use the src elemnt of the script tag to define where the souce of my class is defined. I have removed the namespace declaration but I still have some using statements in the CS file. Is this allowed - I am receiving errors ( Compiler Error Message: CS1519: Invalid token 'using' in class, struct, or interface member declaration) - or must I fully qualify the types in my code? Regards, Jim
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|

You can use both inline code and code-behind code simultaneously on a web page, and even use different languages for each! See example C# and VB combination below. When events are raised, the inline methods receive them first, then the codebehind.
Uncomment the VB section and delete / comment out the C# section to run with different languages.
HTML / Code behind pages are so flexible, that you can build completely new ones of either, replace the original, and as long as the control and event signatures are not broken, all should work when the page is next newly loaded by a client.
Note you need the AutoEventWireup="true" for the inline page to receive events.
<%@ Page Codebehind="WebForm1.aspx.cs" AutoEventWireup="true" Inherits="ScriptTests.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <%-- <script language="VB" runat="server"> Dim _myText As String Sub Page_Load(Sender As Object, e As System.EventArgs) Handles MyBase.Load AddHandler btnTest.Click, AddressOf btnTest_Click txtMyTotal.Text = (Integer.Parse(Me.TextBox1.Text) + Integer.Parse(Me.TextBox2.Text)).ToString() _myText = "Testing" End Sub Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender ' Last chance to update controls with any calculated values from other events End Sub Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) txtMyTotal.Text = _myText End Sub </script> --%> <script language=C# runat=server> string _myText; void Page_Load(object sender, System.EventArgs e) { this.PreRender +=new EventHandler(WebForm1_PreRender); btnTest.Click += new EventHandler(btnTest_Click); txtMyTotal.Text = (int.Parse(this.TextBox1.Text) + int.Parse(this.TextBox2.Text)).ToString(); _myText = "Testing"; } private void WebForm1_PreRender(object sender, EventArgs e) { // Last chance to update controls with any calculated values from other events } void btnTest_Click(object sender, EventArgs e) { txtMyTotal.Text = _myText; } </script> <title>Script Test</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:TextBox id="TextBox1" style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 64px" runat="server">13</asp:TextBox> <asp:TextBox id="TextBox2" style="Z-INDEX: 102; LEFT: 104px; POSITION: absolute; TOP: 104px" runat="server">21</asp:TextBox> <asp:TextBox id="txtMyTotal" style="Z-INDEX: 102; LEFT: 104px; POSITION: absolute; TOP: 144px" runat="server"></asp:TextBox> <asp:button id="btnTest" text="Test" runat="server" /> </form> </body> </HTML>
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
namespace ScriptTests { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.TextBox TextBox2; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here }
#region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }
sbyard : www.pixelda.com
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi sbyard
Yes you can use Both Inline and Code Behind in one Page. Below is another Example of how you can use "Inline Code" in another way
ASPx Page
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="InlineCodeBehind.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body> <form id="Form1" method="post" runat="server"> <asp:Button id="Button1" runat="server" Text="Button1"> <% if (ShouldShowButton2) %> <% { %> <asp:Button id="Button2" runat="server" Text="Button2"> <% } %>
<asp:Button id="Button3" runat="server" Text="Button3"> </form> </body> </HTML>
Code Behind
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
namespace InlineCodeBehind { public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.Button Button2; protected System.Web.UI.WebControls.Button Button3;
/// /// This is just an Example you can do some other logic below /// ShouldShowButton2 Property will be used on the ASPx Page. /// public bool ShouldShowButton2 { get { // Do Some Server call to validate if a user have access to the button return !this.User.Identity.IsAuthenticated; } }
private void Page_Load(object sender, System.EventArgs e) { }
#region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Neil,
First of all...thanks for writing the article. I think you touch on something that hardly any ASP.Net developers are discussing these days. It seems like everyone has accepted codebehind as the standard way of writing ASP.Net applications. I can understand the pros vs. cons of using codebehind, but in an organization where the devlopers are also the web designers, the advantages of separating code from HTML seem less compelling. Additionally, I prefer to not pre-compile my application classes - mainly because we have developers using a vast array of development tools (from Notepad to VS.Net) And, as Ashley indicated earlier, you can change the source and not have to worry about re-compiling.
I would definitely like to hear from others that have tried developing in ASP.Net without using codebehind and compiled classes. I am hoping to try and set this as a standard within our organization, but want to make sure I have considered all of the potential issues before doing so.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Should also be noted that in ASP.net 2.0, codebehind is deprecated, as is inline. The new way to do things in 2.0 is with partial types (frequently called code-besides). It brings a number of advantages to the table...namely solving all the crap problems you get with the above two models...thank god.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Just as a side-note; you can have code behind files without compiling the .cs files to a dll - which i prefer since the recompiling a ddl and refreshing the page is not instant, and thus frustrating!!
unfortunately visual studio doesn't support this very well, so we have to live with this for now. However the new visual studio web developer supports this - about time!!!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Ashley van Gerven wrote: you can have code behind files without compiling the .cs files to a dll
Can you please tell as how?
- - - - - - - - - - - - - - - - - - Memory leaks is the price we pay \0 01234567890123456789012345678901234
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Probably, Ashley van Gerven refers to the use of "SRC" attribute in the @Page directive; it allows you to avoid the explicit build of the code-behind DLL, causing an automatic on-the-fly compilation of each code-behind in a temporary DLL.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanx.! I didn't know you could do that.
- - - - - - - - - - - - - - - - - - Memory leaks is the price we pay \0 01234567890123456789012345678901234
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi all, Thanks for all the response to this article. I Tried to Figure out how to do this as Ashley said. And I can’t get it to work. As soon as I use the src attribute I get errors on my page. The other thing I had a look on the msdn. And it looks to me that the src is not a replacement for Code Behind. But an extension. The page still got the inline code and you can include classes that you want to use. This means that you are still inheriting from system.web.ui.page. The Precompiled DLL is probably your src of the other classes. and not the page it self. Hope this make sense
[Quote] Src Specifies the source file name of the code-behind class to dynamically compile when the page is requested. You can choose to include programming logic for your page either in a code-behind class or in a code declaration block in the .aspx file. Note RAD designers, such as Visual Studio .NET, do not use this attribute. Instead, they precompile code-behind classes and then use the Inherits attribute. [/Quote]
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|