Thursday, 2 February 2012

Code Declaration Blocks | ASP.Net Tutorial | ASP.Net Tutorial PDF

In Next Topic, we’ll talk more about code-behind pages and how they let us separate our application logic from an ASP.NET page’s HTML. However, if you’re not working with code-behind pages, you must use code declaration blocks to contain all the application logic of your ASP.NET page. This application logic defines variables, subroutines, functions, and more. In our sample page, we’ve placed the code inside <script> tags with the runat="server" attribute, like so:

Visual Basic             LearningASP\VB\Hello.aspx(excerpt)
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object,
ByVal e As System.EventArgs)
'set the label text to the current time
myTimeLabel.Text = DateTime.Now.ToString()
End Sub
</script>

C#                              LearningASP\CS\Hello.aspx(excerpt)
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//set the label text to the current time
myTimeLabel.Text = DateTime.Now.ToString();
}
</script>

Comments in VB and C# Code
      Both of these code snippets contain comments—explanatory text that will be ignored by ASP.NET, but which serves to describe to us how the code works.
      In VB code, a single quote or apostrophe (') indicates that the remainder of the line is to be ignored as a comment, while in C# code, two slashes (//) achieve the same end:

Visual Basic                  LearningASP\VB\Hello.aspx(excerpt)
'set the label text to the current time

C#                                   LearningASP\CS\Hello.aspx(excerpt)
//set the label text to the current time

C# code also lets us span a comment over multiple lines if we begin it with /* and end it with */, as in this example:
/*set the label text
to the current time */

<script> Tag Attributes
    Before .NET emerged, ASP also supported such script tags using a runat="server" attribute. However, they could only ever contain VBScript and, for a variety of reasons, they failed to find favor among developers.
     The <script runat="server">tag accepts two other attributes: languageand src. We can set the language that’s used in this code declaration block via the language attribute:

Visual Basic      
<script runat="server"language="VB">

C#
<script runat="server"language="C#">

   If you don’t specify a language within the code declaration block, the ASP.NET page will use the language provided by the languageattribute of the Pagedirective. Each page’s code must be written in a single language; for instance, it’s not possible to mix VB and C# in the same page.
   The second attribute that’s available to us is src; this lets us specify an external code file for use within the ASP.NET page:

Visual Basic
<script runat="server" language="VB" src="mycodefile.vb">

C#
<script runat="server" language="C#"src="mycodefile.cs">