ASP.NET

All Posts related to ASP.NET

Validations:

ASP.NET Validation Server Controls

The RequiredFieldValidator Server Control in asp.net

Validating Drop-Down Lists with the RequiredFieldValidator Control

The CompareValidator Server Control in asp.net

The RangeValidator Server Control in asp.net

The RegularExpressionValidator Server Control in asp.net

The CustomValidator Server Control in asp.net

The ValidationSummary Server Control in asp.net

DataControls:

Datalist control Example in asp.net

Edit,Update&Delete in Gridview using EDM with LINQ

GridView Tooltip and Sorting..

Select All checkbox in gridview

sending all selected items in gridview to next page

Others:

AlbumSlideShow

How to get IP Address of client system

In Line ServerCode

Watermark in textbox using javascript

How to disable Cut,Copy&Paste in ASP.NET TextBox

FileUpload

RadioButton validation

Html5 controls

sending sms using asp.net

scrolling text

Validating Dropdownlist using Javascript

Tree view

FileUpload Validation for Images using RegularExpression

Active Server Pages (ASP)

Introduction

Active Server Pages (ASPs) are Web pages that contain server-side scripts in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags. Server-side scripts are special commands you put in Web pages that are processed before the pages are sent from your Personal Web Server to the Web browser of someone who’s visiting your Web site. . When you type a URL in the Address box or click a link on a Web page, you’re asking a Web server on a computer somewhere to send a file to the Web browser (sometimes called a “client”) on your computer. If that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After receiving the file, your Web browser displays its contents as a combination of text, images, and sounds.

In the case of an Active Server Page, the process is similar, except there’s an extra processing step that takes place just before the Web server sends the file. Before the Web server sends the Active Server Page to the Web browser, it runs all server-side scripts contained in the page. Some of these scripts display the current date, time, and other information. Others process information the user has just typed into a form, such as a page in the Web site’s guestbook.

To distinguish them from normal HTML pages, Active Server Pages are given the “.asp” extension.

VBScript is the default scripting language for ASP, but if you like you can use VBScript, JScript, Perl or any other scripting language for server side scripting in an ASP page. An ASP page is almost the same as a HTM or HTML page… the only difference is that an ASP page has the ‘.asp’ extension. Active Server Page can include both client side and server side scripts. In an ASP page VBScript is usually used as the server side and Java Script as the client side scripting language.

How ASP work?

In Case of a HTM or HTML page.

•  A user requests a web page in the browser (i.e., ‘http://www.nareshit.com/test.htm’)

•  Browser requests the required page from the server (like IIS or PWS).

•  Server reads the required file from memory or the file system and sends it back to the Browser.

•  Browser executes the client side scripting (i.e., Java scripts) and displays the results.

In case of Active Server Page.

•  A user requests a web page in the browser with a file extension .asp
(i.e., ‘http://www.nareshit.com/test.asp’)

•  Browser requests the page from the server (like IIS or PWS).

•  Server reads the required file from memory or the file system and recognizes that the file has
an ‘.asp’ extension.

•  Server sends that file to ASP.dll.

•  ASP.dll reads the file with the ‘.asp’ extension from top to bottom and executes all the codes
within the <% and %> tags and produces a standard HTML page.

•  The server sends that HTML page back to browser.

•  Browser executes the client side scripting (i.e., Java scripts) and displays the results to the
user in the browser window.

Let us take a look at this simple ASP example to get a better idea how ASP works.

HelloWorld.asp

<head>
<title>Hello World</title>
</head>
<body>
<h2>My First ASP Page.</h2>
              <%  For I = 1 To 5  %>
                <font size=”<%=I%>“>Hello World </font>
<br>
              <% Next %>
</body>
</html>

If you request this page in browser this is the result what you will see in the browser as output of this page.

Now if you check “View Source” behind this page you will see something like this.

What happend actually when you requests this page in web browser is, Server reads the file extension and recognize that this is an ASP file and need to execute before send back to browser. ASP.dll reads the file from top to bottom and the executes the code written in between <% and %> tags and browser only gets a result of that server side scripting.

An ASP file normally contains HTML tags, just like an HTML file. However, an ASP file can also contain server scripts, surrounded by the delimiters <% and %>.

Server scripts are executed on the server, and can contain any expressions, statements, procedures, or operators valid for the scripting language you prefer to use.

The response.write Command

The response.write command is used to write output to a browser. The following example sends the text “Hello World” to the browser:

<html>
<body>
<%
response.write(“Hello World!”)
%>
</body>
</html>

Declare a variable
Variables are used to store information. This example demonstrates how to declare a variable, assign a value to it, and use the value in a text.

<html>
<body>

<%
dim name
name=”Donald Duck”
response.write(“My name is: ” & name)
%>

</body>
</html>

Output: My name is: Donald Duck

Declare an array
Arrays are used to store a series of related data items. This example demonstrates how to declare an array that stores names.

There is also a shorthand method for the response.write command. The following example also sends the text “Hello World” to the browser:

<html>
<body>
<%
=”Hello World!”
%>
</body>
</html>

Using Variables, and Forms in Active Server Pages

Forms are a convenient way to communicate with visitors to your Web site. Using forms, you can create a survey form and ask visitors to fill it out. When they fill out the form, you can process the results automatically.

With forms, there are two steps: first you create the form, and then you process it. To create a form for an Active Server Page, just create a standard HTML form.

To try out this example, create an HTML file

<html>
<head><title>Asking for information</title></head>
<body>
<form method=”post” action=”form_response.asp”>
Your name: <input type=”text” name=”name” size=”20″><BR>
Your email: <input type=”password” name=”email” size=”15″><BR>
<input type=”Submit” value=”Submit”>
</form>
</body>
</html>

Active Server Pages provide a mechanism for processing forms.

<html>
<head><title>Responding to a form</title></head>
<body>
Your name is <% =Request.Form(“name”) %> <BR>
Your email is <% =Request.Form(“email”) %>
</body>
</html>

You’ll probably want to do more with your forms than display their contents in a Web page. For example, based on the contents of the form, you may want to create a variable and insert that variable in different places of your response page. You may need to create a variable. To do that, just make up a name and set it equal to the contents of the field.

For example, the form in this example asks users to introduce their names and their favorite color: red, blue, or green. When the form is received, the server responds displaying these data.

<html>
<head><title>Name and Color</title></head>
<body>
<FORM ACTION=”nameandcolor.asp” METHOD=POST>
Let me know your Name and Favorite Color:
<P>YOUR NAME:
<INPUT TYPE=”TEXT” NAME=”YOURNAME” SIZE=20>
<P>COLOR:
<INPUT TYPE=”RADIO” NAME=”COLOR” VALUE=”1″ CHECKED>Red
<INPUT TYPE=”RADIO” NAME=”COLOR” VALUE=”2″>Green
<INPUT TYPE=”RADIO” NAME=”COLOR” VALUE=”3″>Blue
<P>
<INPUT TYPE=”SUBMIT” VALUE=”OK”>
</FORM>
</body>
</html>

Now, create an ASP file as below:

<html>
<head><title>Name and Color</title></head>
<body>
<% TheName = Request.Form(“YOURNAME”) %>
<% colornumber = Request.Form(“COLOR”) %>
Hi, <% =Thename %>.<BR>
I know your favorite color is
<% if colornumber = “1” then %>
red
<% end if %>
<% if colornumber = “2” then %>
green
<% end if %>
<% if colornumber = “3” then %>
blue
<% end if %>.
</body>
</html>

If….Then…Else

The If….Then…Else instructions sequence is very similar to the one we may find in different kind of scripting languages. Let’s check an example.

<%
AA=”water”

If AA=”water” Then
response.write (“I want to drink water”)
Else
response.write (“I want to drink milk”)

End If
%>

For….Next

This instructions is also similar in different programming languages. Let’s see a typical example.

I want to say “Hello” 10 times<BR>
<% For mynumber = 1 to 10 %>
<% =mynumber %> Hello<BR>
<% Next %>
END

Subroutines

Subroutines have the same utility in ASP as it has in other languages. The use of subroutines may be very useful when there are a lot of instructions to be perform within a subroutine. This way it will allow us to simplify the structure of our script.   The Subroutine statements will be enclosed within Sub.. End Sub statements.

<%
TheName=request.form(“name)

if TheName=”John” then
ResponseToJohn()
else
ResponseToUnknown()
end if

Sub ResponseToJohn()
response.write (“Hi, John. How are you?”)
response.write (“<br>Did you know I got married last month?”)
End Sub

Sub ResponseToUnknown()
response.write (“Hi. How are you?”)
End Sub %>

Include/virtual

Server Site includes or SSI is a very simple programing language but it also has a very limited number of instructions.

response.asp

<%
TheName=request.form(“name)

if TheName=”John” then
%>
<!–#include virtual=”/file1.html” –>
<% else %>
<!–#include virtual=”/file2.asp” –>
<%
end if %>

File1.html

Hi, John.<br>
I know your are 31 years old, you are married to Sue, and you are living in New York.

File2.asp

<%  for i=1 to 3
response.write(Thename & “…<BR>”)
next
response.write(“Who are you?”)
%>

Intrinsic ASP Objects

ASP would be useless if it couldn’t interact with the web browser and the web server. There are five programming objects that are always accessible from an ASP page, Request, Response, Server, Session and Application. These objects are implicitly created if you use any of their methods.

The only method from one of these objects that has been introduced so far has been the Write method from the Response object, which writes text to the outputted HTML file. In general, the Response object adds information to what the server sends back to the client’s browser. The Request object obtains extra information from the client. The Server object allows the programmer to instantiate objects through the web server, as well as perform some utility functions. The Session object controls the ASP Session, which is by default defined as any page views from one client such that 20 minutes without visiting a page have not elapsed. Finally, the Application object deals with information and variables that apply to all clients concurrently accessing the ASP site.

Object Description
Application Stores information (variables and objects) needed for all users of a particular application. Information stored in the Application object persists for the lifetime of the application.
ASPError Reports error information.
Request Provides access to values passed to the server by the client.
Response Controls the output from an ASP script to the requesting client.
Server Provides access to methods and properties on the server. These methods and properties typically serve as utility functions.
Session Stores information (variables and objects) needed for a particular user session. Information stored in the Session object is not discarded when the user jumps between pages in the application, but instead persists for the entire user session.

ASP Response Object

The Response object controls sending output to the browser.

            Response.collection | property | method

ASP Request Object

The Request object retrieves the values that the browser passed to the server during an HTTP request.

            Request.[collection | property | method ](variable)

ASP Server Object

The Server object provides access to methods and properties on the server. Most of its methods and properties serve as utility functions.

            Server.property property | method

ASP Application Object
The ASP Application object shares information among all users of a given application. An ASP-based application is defined as all .asp files in a virtual directory and associated sub-directories. Because the Application object can be shared by more than one user, Lock and Unlock methods are provided to ensure that multiple users cannot alter a property simultaneously.

ASP Session Object

One of the challenges faced by Web developers is how to create a coherent application out of a series of independent HTML pages. This problem is a particular concern in Web development because HTTP is a stateless protocol. Each browser request to a Web server is independent, and the server retains no memory of a browser’s past requests. The HTTP 1.0 protocol did not provide a mechanism to maintain state information between requests from a browser.

To overcome this limitation, application developers require a technique to provide consistent user sessions on the Web. Active Server Pages (ASP) provides powerful and flexible Web session management that requires no special programming. The Session object, one of the intrinsic objects supported by ASP, provides a developer with a complete Web session management solution.

The Session object supports a dynamic associative array that a script can use to store information. Scalar variables and object references can be stored in the session object.

The Session object stores information needed for a particular user-session.

Variables stored in the Session object are not discarded when the user jumps between pages in the application, but rather persist for the entire user-session. The Web server automatically creates a Session object when a Web page (from a server application) is requested by a user who does not already have a session. The server destroys the Session object when the session expires or is abandoned.

Session.collection | property | method

Example:

Session (“UserName”) = “Naresh”

Would store the string “Naresh” in the Session object and give it the name “UserName.” This value can be retrieved from the Session object by referencing the Session object by name, as in the following:

Welcome back <% = Session(“UserName”) %>

ASP also provides session-specific events that can trigger your own session initialization and clean up code. Each time a new session begins, the procedure Session_OnStart is called. An ASP program can use this event to perform any required session initialization tasks. Any time a session ends, whether it was timed out by the server, or killed by calling Session.Abandon, the procedure Session_OnEnd is called. An ASP program can use this event to perform any session cleanup that is required.

ASPError Object

The ASPError object reports error information, and can be used to obtain information about an error condition that has occurred in script in an ASP page. The ASPError object is returned by the Server.GetLastError method. It has no methods but exposes several read-only properties, which provide specific information about the error the object represents.

               ASPError.property

<%
dim objErr
set objErr=Server.GetLastError()
response.write(“ASPCode=” & objErr.ASPCode)
response.write(“<br />”)
response.write(“ASPDescription=” & objErr.ASPDescription)
response.write(“<br />”)
response.write(“Category=” & objErr.Category)
response.write(“<br />”)
response.write(“Column=” & objErr.Column)
response.write(“<br />”)
response.write(“Description=” & objErr.Description)
response.write(“<br />”)
response.write(“File=” & objErr.File)
response.write(“<br />”)
response.write(“Line=” & objErr.Line)
response.write(“<br />”)
response.write(“Number=” & objErr.Number)
response.write(“<br />”)
response.write(“Source=” & objErr.Source)
%>

Global.asa

Global.asa is a text file locate in your main directory (/global.asa). Bellow is shown the basic extructure of a global.asa file.

<SCRIPT LANGUAGE=”VBScript” RUNAT=”Server”>

Sub Application_OnStart
……..
End Sub

Sub Application_OnEnd
……..
End Sub

Sub Session_OnStart
……..
End Sub

Sub Session_OnEnd
……..
End Sub

</SCRIPT>

This file will be activated in this cases:

  • When the first visitor accesses our pages
  • When a new session starts.

In both cases, we may determine a series of events to be execute in the file above.

  1. Application_OnStart
    It is execute before the first session is started.
  2. Application_OnEnd
    It is execute when the application is finished.
  3. Session_OnStart
    It is execute when the server creates a new session (when a new client acccesses our server).
  4. Session_OnEnd
    It is execute when a session is abandon of after certain period of time without contact between the client and the server (normaly after 20 minutes or so from the last request from a specific client, the server will consider he is not going to come back, so it will delete all the information related to that session).

Active Users Counter

Just copy the code in the table to a text file and save it in the main directory of your site (“/global.asa”).

<SCRIPT LANGUAGE=”VBScript” RUNAT=”Server”>

Sub Application_OnStart
application(“visitors”)=0
End Sub

Sub Application_OnEnd
End Sub

Sub Session_OnStart
application.lock
application(“visitors “)=application(“visitors “)+1
application.unlock
End Sub

Sub Session_OnEnd
application.lock
application(“visitors “)=application(“visitors “)-1
application.unlock
End Sub

</SCRIPT>

The first time a visitor gets to our pages, global.asa will be executed, and consequently, application(“visitors“) in line 4 will get a value equal to “0”. Immediately (as a new session has started),  application(“visitors“) will be increased by one. Each time a new visitor gets to our pages application(“visitors”) will be increased by one, and identically, each time a session is finished, this parameter will be reduce by one.

Deploying an ASP Application into IIS

How to Copy an ASP Application to the Destination Computer

To deploy the ASP application on the destination computer, you must first copy the ASP application files from the source computer to the destination computer. The easiest way to copy the files is to use Windows Explorer.

Share the Folder on Your Source Computer That Contains Your Web Application

You must share the ASP application folder on the source computer so that you can access it from destination computer. To share the ASP application folder on the source computer, follow these steps:

  1. Log on to the source computer as Administrator or a user who is in the local Administrators group.
  2. From the Start menu, click Run, type explorer to open Windows Explorer. Click OK.
  3. Select the folder in which the ASP files that you want to copy are located.
  4. Right-click the name of the folder that you selected in step 3. In the resultant shortcut menu, click Sharing.
  5. Click Share this folder, and provide a new name for the share if you want. The default name is the name of that folder.
  6. Click Permissions, select Everyone, make sure that the Read check box is selected and that the other check boxes are cleared, and then click OK.
  7. In the Sharing properties dialog box, click OK.

Create a Destination Folder and Copy the Files

To copy the contents of the shared folder from the source computer to the destination computer, follow these steps:

  1. On the destination computer, from the Start menu, click Run, type explorer, and then click OK. Refer to this Windows Explorer window “Window A.”
  2. In Window A, browse to your Wwwroot folder. By default, this is located at C:\Inetpub\Wwwroot.
  3. Your destination folder is either Wwwroot or a folder one level beneath it. If the destination folder does not exist, create a new folder one level beneath the Wwwroot folder to serve as the destination folder.
  4. From the Start menu, click Run, and type \\<SourceComputername>\<Sharename>, and then click OK. For example, if the source computer name is “ComputerA” and you created a share called “ASP” on that computer, type \\ComputerA\ASP. If you are prompted for a user name and password to connect to the source computer, type the user name as Administrator or any other user who is in the Administrators group on the source computer, type the password, and then click OK. If the user name and password that you supplied are correct, a window displays the files and folders on that shared folder. Call this window “Window B.”
  5. Select all of the files and folders from Window B. To select all of the files and folders, click in the blank area of Window B, and press the CTRL+A key combination. Then press CTRL+C to copy all of the files and folders.
  6. In Window A, right-click the destination folder, and then click Paste. This copies all of the files and folders that you selected in Window B to the new folder.
  7. After you successfully copy the application and related files and folders, you must remove the share(s) that you created on the source computer.

How to Configure the Folder as an ASP Application

To configure the folder as an ASP application, follow these steps:

  1. From the Start menu, point to Programs, point to Administrative Tools, and then click Internet Services Manager.
  2. In the Internet Services Manager, double-click the destination computer name.
  3. If necessary, double-click to expand your Web site so that you can view the directories one level beneath it. Within Internet Services Manager, your Web site is named Default Web Site by default.
  4. The directories are not always listed in alphabetical order. If your directory is not listed, close and re-open Internet Services Manager, and look again. This updates Internet Services Manager with the most recent changes.
  5. In Internet Services Manager, right-click your directory, and then click Properties.
  6. On the Directory tab, locate the Create or Remove button. If the button is labeled Remove, proceed to the next step. If the button is labeled Create, click it.
  7. On the Directory tab, click Scripts Only in the Execute Permissions drop-down list box, and then click Configuration.
  8. On the App Options tab, select or clear the Enable Session State check box depending on whether you use session variables in your Web application.

If you select the Enable Session State check box, you must also type the number of minutes that a session is kept in memory on the server. If users browse to an ASP page in your application, they start a session. If they do not browse to additional ASP pages in your application (they become inactive), their session variables are purged after this amount of time.

  1. Click OK to return to the Properties dialog box.
  2. Click the Documents tab. This tab determines which page is used if users type the URL to your Web application without specifying a page. You may enable or disable this option, and you may add or remove items from the list of pages. If you enable this option, IIS looks for the first page that is listed. If IIS cannot find this page, it looks for the second page, and so on.
  3. Click OK to save your changes and close the Properties dialog box.
  4. Close Internet Services Manager. Deployment is complete.

Test the Web Application on the New Server

To verify that the deployed ASP application works on the destination computer, follow these steps:

  1. From the Start menu, click Run, type http://&lt;destinationComputerName>/<yourApplicationName>/, and then click OK.
  2. The default page for your application appears in the browser.
  3. Try to browse to other pages in the application.

ASP.NET Compilation Overview

In order for application code to service requests by users, ASP.NET must first compile the code into one or more assemblies. Assemblies are files that have the file name extension .dll. You can write ASP.NET code in many different languages, such as Visual Basic, C#, J#, and others. When the code is compiled, it is translated into a language-independent and CPU-independent representation called Microsoft Intermediate Language (MSIL). At run time, MSIL runs in the context of the .NET Framework, which translates MSIL into CPU-specific instructions for the processor on the computer running the application

There are many benefits to compiling application code including:

  • Performance   Compiled code is much faster than scripting languages such as ECMAScript or VBScript because it is a closer representation to machine code and does not require additional parsing.
  • Security   Compiled code is more difficult to reverse engineer than non-compiled source code because it lacks the readability and abstraction of a high-level language. Additionally, there are obfuscation tools that make compiled code even more resistant to reverse engineering.
  • Stability   Code is checked at compile time for syntax errors, type safety, and other problems. By catching these errors at build-time you can eliminate many errors in your code.
  • Interoperability   Because MSIL code supports any .NET language, you can use assemblies that were originally written in other languages in your code. For example, if you are writing an ASP.NET Web page in C#, you can add a reference to a .dll file that was written in Visual Basic.

The ASP.NET compilation architecture includes a number of features including:

  • Multiple language support.
  • Automatic compilation.
  • Flexible deployment.
  • Extensible build system.

Directory structure

In general, the ASP.NET directory structure can be determined by the developer’s preferences. Apart from a few reserved directory names, the site can span any number of directories. The structure is typically reflected directly in the urls. Although ASP.NET provides means for intercepting the request at any point during processing, the developer is not forced to funnel requests through a central application or front controller.

The special directory names (from ASP.NET 2.0 on) are as below:

App_Browsers 

holds site-specific browser definition files.

 

App_Code 

This is the “raw code” directory. The ASP.NET server automatically compiles files (and subdirectories) in this folder into an assembly which is accessible in the code of every page of the site. App_Code will typically be used for data access abstraction code, model code and business code.

App_Data 

default directory for databases, such as Access mdb files and SQL Server mdf files. This directory is usually the only one with write access for the application.

App_LocalResources 

Contains localized resource files for individual pages of the site. E.g. a file called CheckOut.aspx.fr-FR.resx holds localized resources for the French version of the CheckOut.aspx page. When the UI culture is set to french, ASP.NET will automatically find and use this file for localization.

App_GlobalResources 

Holds resx files with localized resources available to every page of the site. This is where the ASP.NET developer will typically store localized messages etc. which are used on more than one page.

App_Themes 

holds alternative themes of the site.

App_WebReferences 

holds discovery files and WSDL files for references to web services to be consumed in the site.

Bin 

Contains compiled code (.dll files) for controls, components, or other code that you want to reference in your application. Any classes represented by code in the Bin folder are automatically referenced in your application.

ASP.NET compared to ASP classic:

ASP.NET attempts to simplify developers’ transition from Windows application development to web development by offering the ability to build pages composed of controls similar to a Windows user interface. A web control, such as a button or label, functions in very much the same way as its Windows counterpart: code can assign its properties and respond to its events. Controls know how to render themselves: whereas Windows controls draw themselves to the screen, web controls produce segments of HTML and JavaScript which form part of the resulting page sent to the end-user’s browser.

ASP.NET encourages the programmer to develop applications using an event-driven GUI model, rather than in conventional web-scripting environments like ASP and PHP. The framework attempts to combine existing technologies such as JavaScript with internal components like “ViewState” to bring persistent (inter-request) state to the inherently stateless web environment.

Other differences compared to ASP classic are:

  • Compiled code means applications run faster with more design-time errors trapped at the development stage.
  • Significantly improved run-time error handling, making use of exception handling using try-catch blocks.
  • Similar metaphors to Microsoft Windows applications such as controls and events.
  • An extensive set of controls and class libraries allows the rapid building of applications, plus user-defined controls allow commonly-used web template, such as menus. Layout of these controls on a page is easier because most of it can be done visually in most editors.
  • ASP.NET leverages the multi-language capabilities of the .NET Common Language Runtime, allowing web pages to be coded in VB.NET, C#, J#, etc.
  • Ability to cache the whole page or just parts of it to improve performance.
  • Ability to use the code-behind development model to separate business logic from presentation.
  • in ASP.NET can be saved in a Microsoft SQL Server database or in a separate process running on the same machine as the web server or on a different machine. That way session values are not lost when the web server is reset or the ASP.NET worker process is recycled.
  • Versions of ASP.NET prior to 2.0 were criticized for their lack of standards compliance. The generated HTML and JavaScript sent to the client browser would not always validate against W3C/ECMA standards. However, in version 2.0, all controls generate valid HTML 4.0, XHTML 1.0 (the default) or XHTML 1.1 output, depending on the site configuration. Detection of standards-compliant web browsers is more robust and support for Cascading Style Sheets is more extensive.
  • Web Server Controls: these are controls introduced by ASP.NET for providing the UI for the web form. These controls are state managed controls and are WYSIWYG controls.

ASP.NET Page Class Overview

When an ASP.NET page is requested and renders markup to a browser, the code that runs is not solely the code that you created for your page. Instead, at run time, ASP.NET generates and compiles one or more classes that actually perform the tasks required to run the page.

Generating and Running the Page Class Code

An ASP.NET page runs as a unit, combining the server-side elements in a page, such as controls, with the event-handling code you have written. You do not have to precompile pages into assemblies. ASP.NET dynamically compiles pages and runs them the first time they are requested by a user. If there are any changes to the page or resources the page depends on, the page is automatically recompiled. The class or classes that the compiler creates depends on whether the page uses the single-file model or the code-behind model.

ASP.NET also supports precompilation of a Web site to enhance performance and perform error checking as well as to support site deployment.

Single-File Pages

In a single-file page, the markup, server-side elements, and event-handling code are all in a single .aspx file. When the page is compiled, the compiler generates and compiles a new class that derives from the base Page class or a custom base class defined with the Inherits attribute of the @ Page directive. For example, if you create a new ASP.NET Web page named SamplePage1 in your application’s root directory then a new class named ASP.SamplePage1_aspx is derived from the Page class.

The following illustration shows the inheritance model for the page class in a single-file ASP.NET Web page:

Code-Behind Pages

In the code-behind model, the page’s markup and server-side elements, including control declarations, are in an .aspx file, while your page code is in a separate code file. The code file contains a partial class—that is, a class declaration with the keyword partial (Partial in Visual Basic) indicating that it contains only some of the total code that makes up the full class for the page. In the partial class, you add the code that your application requires for the page. This typically consists of event handlers, but can include any methods or properties that you need.

  1. The code-behind file contains a partial class that inherits from a base page class. The base page class can be the Page class, or it can be another class that derives from Page.
  2. The .aspx file contains an Inherits attribute in the @ Page directive that points to the code-behind partial class.
  3. When the page is compiled, ASP.NET generates a partial class based on the .aspx file; this class is a partial class of the code-behind class file. The generated partial class file contains declarations for the page’s controls. This partial class enables your code-behind file to be used as part of a complete class without requiring you to declare the controls explicitly.
  1. Finally, ASP.NET generates another class that inherits from the class generated in Step 3. This second generated class contains the code required to build the page. The second generated class and the code-behind class are compiled into an assembly that runs to render output to the browser.

The following illustration shows the inheritance model for the page class in a code-behind ASP.NET Web page:

Working with Server Controls

When you create ASP.NET Web pages, you can use these types of controls:

  • HTML server controls   HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render.
  • Web server controls   Controls with more built-in features than HTML server controls. Web server controls include not only form controls such as buttons and text boxes, but also special-purpose controls such as a calendar, menus, and a tree view control. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax.
  • Validation controls   Controls that incorporate logic to enable you to what users enter for input controls such as the TextBox control. Validation controls enable you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on.
  • User controls   Controls that you create as ASP.NET Web pages. You can embed ASP.NET user controls in other ASP.NET Web pages, which is an easy way to create toolbars and other reusable elements.

The System.Web.UI.WebControls namespace contains a collection of classes that allow you to create Web server controls on a Web page. You can programmatically control the Web server controls because they run on the server.  System.Web.UI.Control is the base class for several simpler controls, such as Literal, Placeholder, Repeater, and Xml.

These properties and methods are present in all controls that inherit from System.Web.UI.Control, which includes all the controls in System.Web.UI.WebControls. The controls that derive directly from System.Web.UI.Control are described in the following sections.

Literal

The Literal control reserves a location for static text on a Web Form.  The Literal control is rarely used, because the Label control is more often used to display static text.

PlaceHolder

The PlaceHolder control holds dynamically added server controls to the page at a particular location. You might wonder why such a control is required. In Classic ASP, when you added an HTML control to a page, you would often use Response.Write() to write out the HTML required for a new control.

To see the PlaceHolder control in action, added a PlaceHolder control to the new page by dragging it from the Toolbox onto the form in Design view. Then I pressed F7 to open the code for the page and added the following lines to the Page_Load event.

System.Web.UI.WebControls.TextBox tb = new TextBox();

tb.ID = “tb”;

tb.Text = “Hello World”;

this.PlaceHolder1.Controls.Add(tb);

The two properties that I set here are not strictly required. However, you should usually set the ID property so that you can identify the control when handling a postback.

A page with a text box added to a PlaceHolder control in the Page_Load event handler

Note that the PlaceHolder control, added in Design view, does not render any HTML. The text box (named tb, with text set to Hello World) is placed where the placeholder was in the .aspx page.

Checkbox

The Checkbox control is used to select a true or false value. The Checkbox control is usually rendered as a box that toggles a check mark in the box when clicked.

RadioButton

The RadioButton control inherits directly from the Checkbox control, so the two controls are similar. The RadioButton control is often rendered as a circle, and when clicked, a dot inside the circle toggles. When two or more radio buttons are placed together, any currently selected button is deselected when any one of the buttons is clicked.

HyperLink

The HyperLink control creates a link on a Web page, commonly used to allow a user to jump to another page.

Image

The Image control allows you to display an image on the page.

ImageButton

The ImageButton control’s base class is the Image control just described. The ImageButton control is rendered much like an Image control, and it behaves in a way that might seem similar to the HyperLink control. The difference is that rather than redirecting the user to another page, the ImageButton control causes a post back to the page on which the control resides. The ImageButton control does this by using JavaScript; if JavaScript is disabled, or if the underlying JavaScript is in some way broken, the ImageButton control will not work.

Label

The Label control is used to display text in a way very similar to the Literal control previously described. The distinction between the Label and the Literal controls is primarily that the Label control contains the properties that it inherits from the WebControl class for greater control over the appearance of rendered text.

Panel

The Panel control acts as a container for other controls. Using a Panel control allows you to control the visibility of a group of controls at once. This can be useful when you select an option on a form that might require entry of additional fields. The panel can be made visible or invisible based on an entry in another field.

TextBox

The workhorse of the Web controls is the TextBox control. The TextBox control allows the user to enter text, and it can be rendered as a simple text box, as a multiline text box (an HTML TextArea control), or a password text box.

Calendar

A common requirement for any data entry screen, whether Web Form or Microsoft Windows Form, is date entry. The Calendar control displays a single month at a time, and it allows the user to navigate between months.

 The Calendar Tasks menu in Visual Studio 2005

ListControl

The ListControl class is an abstract class that acts as a base for all list controls. An abstract class is a class that is incomplete, with at least one method that has no implementation, and thus cannot be directly instantiated or used. List controls are an important element of most applications. Often list controls are bound to a database table or view.

DropDownList

The DropDownList control, which descends directly from the ListControl abstract class, appears in the browser to be similar to the ComboBox control used in Windows Forms applications. The similarity is superficial, however. Unlike the ComboBox control, which can allow entry of arbitrary text into the text box at the top of the control when so configured, the DropDownList control only allows selection of an item from the list. ComboBox controls often allow incremental searches as well. So, if I enter “R” in one of these ComboBox controls, the list advances to the first entry starting with “R.” If I type “e,” the list advances to the first entry starting with “Re,” and so on. Enter the same characters in the DropDownList control, and the list moves to the first name starting with “e” as I type “e,” ignoring the previously entered “R.” The only properties added by the DropDownList control are BorderColor, BorderStyle, and BorderWidth, which do exactly what you would expect.

 ListBox

The ListBox control is similar to the DropDownList control. The ListBox control looks like the bottom portion of the DropDownList control when the list is showing. ListBox is a control that can be used when multiple selections are required. Multiple selections can be made using Ctrl+Click and Shift+Click actions, exactly as with standard Windows controls. Ctrl+Click allows selection of random items in a list, and Shift+Click allows selection of a region of the list.

 RadioButtonList

The RadioButtonList control provides a convenient way to display a list of mutually exclusive choices. Using a RadioButtonList control is much more convenient than adding several option button controls together on a form.

 CheckBoxList

The CheckBoxList control provides a convenient way to display a list of choices that allow selection of multiple items. Using a CheckBoxList control is much more convenient than adding several Checkbox controls together on a form. The CheckBoxList control adds the same additional properties as the RadioButtonList control.


Download ASP.NET Full Material

Asp.Net Main Meterial

you can see all asp.net posts by clicking on asp.net category…



3 thoughts on “ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s