Thursday, 2 February 2012

View State | ASP.Net Tutorial | ASP.Net Tutorial PDF

   ASP.NET controls automatically retain their data when a page is sent to the server in response to an event (such as a user clicking a button). Microsoft calls this persistence of data view state. In the past, developers would have had to resort to hacks to have the application remember the item a user had selected in a drop-down menu, or store the content entered into a text box; typically, these hacks would have relied on hidden form fields.
   This is no longer the case. Once they’re submitted to the server for processing, ASP.NET pages automatically retain all the information contained in text boxes and drop-down lists, as well as radio button and checkbox selections. They even keep track of dynamically generated tags, controls, and text. Consider the following code written in the “ancient” ASP (not ASP.NET!) framework:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Sample Page using VBScript</title>
</head>
<body>
<form method="post" action="sample.asp">
<input type="text" name="nameTextBox"/>
<input type="submit" name="submitButton" value="Click Me" />
<%
If Request.Form("nameTextBox") <> "" Then
Response.Write(Request.Form("nameTextBox"))
End If
%>
</form>
</body>
</html>
         Loading this page through an ASP-enabled web server (such as IIS) would reveal that the view state is not automatically preserved. When the user submits the form, the information that was typed into the text box is cleared, although it’s still available in the Request.Form("nameTextBox") property. The equivalent page in ASP.NET demonstrates this data persistence using view state:
Visual Basic               LearningASP\VB\ViewState.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Click(ByVal s As Object, ByVal e As EventArgs)
messageLabel.Text = nameTextBox.Text
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>View State Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="nameTextBox" runat="server" />
<asp:Button ID="submitButton" runat="server"
Build Your Own ASP.NET 3.5 Web Site Using C# & VB (www.sitepoint.com)
ASP.NET Basics 39
Text="Click Me" OnClick="Click" />
<asp:Label ID="messageLabel" runat="server" />
</div>
</form>
</body>
</html>

C#                          LearningASP\CS\ViewState.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Click(Object s, EventArgs e)
{
messageLabel.Text = nameTextBox.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>View State Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox id="nameTextBox" runat="server" />
<asp:Button id="submitButton" runat="server"
Text="Click Me" OnClick="Click" />
<asp:Label id="messageLabel" runat="server" />
</div>
</form>
</body>
</html>
       In this case, the code uses ASP.NET controls with the runat="server" attribute. As you can see in below Figure, the text from the box appears on the page when the button is clicked, but also notice that the data remains in the text box! The data in this example is preserved by view state.

          Figure : ASP.NET maintaining the state of the controls
      You can see the benefits of view state already. But where’s all that information stored?
ASP.NET pages maintain view state by encrypting the data within a hidden form field. View the source of the page after you’ve submitted the form, and look for the following code:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUKLTEwNDY1Nzg0MQ9…0fMCR+FN5P6v5pkTQwNEl5xhBk" />

       This is a standard HTML hidden form field. All information that’s relevant to the view state of the page is stored within this hidden form field as an encrypted string.
        View state is enabled for every page by default. If you don’t intend to use view state, you can turn it off, which will result in a slight performance gain in your pages. To do this, set the EnableViewState property of the Page directive to false:
<%@ Page EnableViewState="False" %>

Literal Text and HTML Tags | ASP.Net Tutorial | ASP.Net Tutorial PDF

The final elements of an ASP.NET page are plain old text and HTML. Generally, you can’t do without these elements—after all, HTML allows the display of the information in your ASP.NET controls and code in a way that’s suitable for users and their browsers. Let’s take a look at the literal text and HTML tags that were used to produce the display in the Visual Basic version of our sample page (the text and HTML in the C# version is identical):
Visual Basic                 LearningASP\VB\Hello.aspx(excerpt)
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
myTimeLabel.Text = DateTime.Now.ToString()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Welcome to Build Your Own ASP.NET 3.5 Web Site!</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Hello there!</p>
<p>
The time is now:
<%-- Display the current date and time --%>
<asp:Label ID="myTimeLabel" runat="server" />
</p>
<p>
<%-- Declare the title as string and set it --%>
<% Dim Title As String = "This is generated by a code
render block."%>
<%= Title %>
</p>
</div>
</form>
</body>
</html>

     The bold code above highlights the fact that literal text and HTML tags provide the structure for presenting our dynamic data. Without these elements, this page would have no format, and the browser would be unable to understand it.
    By now, you should have a clearer understanding of the structure of an ASP.NET page. As you work through the examples in this book, you’ll begin to realize that, in many cases, you won’t need to use all of these elements. For the most part, your development will be modularized within code-behind files or code declaration blocks, and all of the dynamic portions of your pages will be contained within code render blocks or controls located inside a <form runat="server"> tag.
     In the following sections, we’ll explore view state, discuss working with directives, and shine a little light on the languages that can be used within ASP.NET.

Server-side Comments | ASP.Net Tutorial | ASP.Net Tutorial PDF

   Server-side comments allow you to include within the page comments or notes that won’t be processed by ASP.NET. Traditional HTML uses the <!--and -->character sequences to delimit comments; any information included between these tags won’t be displayed to the user. ASP.NET comments look very similar, but use the sequences <%--and --%>.
    Our ASP.NET example contains two server-side comment blocks, the first of which is the following:

                                 LearningASP\VB\Hello.aspx (excerpt)
<%-- Display the current date and time --%>
The difference between ASP.NET comments and HTML comments is that ASP.NET comments are not sent to the client at all; HTML comments are, so they’re not suited to commenting out ASP.NET code. Consider the following example:

C#
<!-<%
string Title = "This is generated by a code render block."; %>
<%= Title %>
-->
       Here, it looks as though a developer has attempted to use an HTML comment to stop a code render block from being executed. Unfortunately, HTML comments will only hide information from the browser, not the ASP.NET runtime. So in this case, although we won’t see anything in the browser that represents these two lines, they will be processed by ASP.NET, and the value of the variable Title will be sent to the browser inside an HTML comment, as shown here:
<!-This
code generated by a code render block.
-->
The code could be modified to use server-side comments very simply:
C#
<%--
<% string Title = "This is generated by a code render block."; %>
<%= Title %>
--%>
    The ASP.NET runtime will ignore the contents of this comment, and the value of the Title variable will not be output.

ASP.NET Server Controls | ASP.Net Tutorial | ASP.Net Tutorial PDF

    At the heart of any ASP.NET page lie server controls, which represent dynamic elements with which your users can interact. There are three basic types of server control: ASP.NET controls, HTML controls, and web user controls.
    Usually, an ASP.NET control must reside within a <form runat="server"> tag in order to function correctly. Controls offer the following advantages to ASP.NET developers:
  • They give us the ability to access HTML elements easily from within our code: we can change these elements’ characteristics, check their values, or even update them dynamically from our server-side programming language of choice.
  • ASP.NET controls retain their properties thanks to a mechanism called view state. We’ll be covering view state later in this chapter. For now, you need to know that view state prevents users from losing the data they’ve entered into a form once that form has been sent to the server for processing. When the response comes back to the client, text box entries, drop-down list selections, and so on are all retained through view state.
  • With ASP.NET controls, developers are able to separate a page’s presentational elements (everything the user sees) from its application logic (the dynamic portions of the ASP.NET page), so that each can be maintained separately.
  • Many ASP.NET controls can be “bound” to the data sources from which they will extract data for display with minimal (if any) coding effort.
ASP.NET is all about controls, so we’ll be discussing them in greater detail as we move through this book. In particular, Chapter 4 explains many of the controls that ship with ASP.NET. For now, though, let’s continue our dissection of an ASP.NET page.

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

       You can use code render blocks to define inline code or expressions that will execute when a page is rendered. Code within a code render block is executed immediately when it is encountered during page rendering. On the other hand, code within a code declaration block (within <script> tags) is executed only when it is called or triggered by user or page interactions. There are two types of code render blocks—inline code, and inline expressions—both of which are typically written within the body of the ASP.NET page.

         Inline code render blocks execute one or more statements, and are placed directly inside a page’s HTML between <% and %> delimiters. In our example, the following is a code render block:

Visual Basic                   LearningASP\VB\Hello.aspx(excerpt)
<% Dim Title As String = "This is generated by a code renderblock." %>

C#                                 LearningASP\CS\Hello.aspx(excerpt)
<% string Title = "This is generated by a code render block."; %>

      These code blocks simply declare a String variable called Title, and assign it the value This is generated by a code render block.
      Inline expression render blocks can be compared to Response.Write in classic ASP. They start with <%= and end with %>, and are used to display the values of variables and the results of methods on a page. In our example, an inline expression appears immediately after our inline code block:

Visual Basic            LearningASP\VB\Hello.aspx(excerpt)
<%= Title %>

C#                           LearningASP\CS\Hello.aspx(excerpt)
<%= Title %>
       If you’re familiar with classic ASP, you’ll know what this code does: it simply outputs the value of the variable Title that we declared in the previous inline code block.

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">

Directives | ASP.Net Tutorial | ASP.Net Tutorial PDF

    The directives section is one of the most important parts of an ASP.NET page. Directives control how a page is compiled, specify how a page is cached by web browsers, aid debugging (error-fixing), and allow you to import classes to use within your page’s code. Each directive starts with <%@. This is followed by the directive name, plus any attributes and their corresponding values. The directive then ends with %>.

     There are many directives that you can use within your pages, and we’ll discuss them in greater detail later. For the moment, however, know that the Import and Page directives are the most useful for ASP.NET development. Looking at our sample ASP.NET page, Hello.aspx, we can see that a Page directive was used at the top of the page like so:

Visual Basic                LearningASP\VB\Hello.aspx (excerpt)
<%@ Page Language="VB" %>

C#                              LearningASP\CS\Hello.aspx(excerpt)
<%@ Page Language="C#" %>
     In this case, the Pagedirective specifies the language that’s to be used for the application logic by setting the Language attribute. The value provided for this attribute, which appears in quotes, specifies that we’re using either VB or C#. A whole range of different directives is available; we’ll see a few more later in this chapter.
     ASP.NET directives can appear anywhere on a page, but they’re commonly included at its very beginning.