Вы находитесь на странице: 1из 18

UNIT-I

Web Applications: Are Programs that can be executed either on a Web Server or in a Web Browser. Can support online commerse. Dynamic Web Page Client-side Scripting: Enable to develop Web pages can dynamically respond to user input without having the interact with Web Server. Help in reducing network traffic. Speed up the response time of a Web Application commercial transactions, popularly known as e-

Server-side Scripting: Server-side Scripting provides Dynamic content to users based on the information stored in a remote location.

Overview of ASP.NET framework ASP.NET and the .NET Framework

Aryan Thakur

AryansNetwork@gmail.com

ASP.NET is part of the Microsoft .NET Framework. To build ASP.NET pages, you need to take advantage of the features of the .NET Framework. The .NET Framework consists of two parts: the Framework Class Library and the Common Language Runtime. Framework Class Library The .NET Framework contains thousands of classes that you can use when building an application. The Framework Class Library was designed to make it easier to perform the most common programming tasks. Here are just a few examples of the classes in the framework:

File class Enables you to represent a file on your hard drive. You can use the File class to check whether a file exists, create a new file, delete a file, and perform many other file related tasks. Graphics class Enables you to work with different types of images such as GIF, PNG, BMP, and JPEG images. You can use the Graphics class to draw rectangles, arcs, ellipsis, and other elements on an image. Random class Enables you to generate a random number. SmtpClient class Enables you to send email. You can use the SmtpClient class to send emails that contain attachments and HTML content.

These are only four examples of classes in the Framework. The .NET Framework contains almost 13,000 classes you can use when building applications. Common Language Runtime The second part of the .NET Framework is the Common Language Runtime (CLR). The Common Language Runtime is responsible for executing your application code. When you write an application for the .NET Framework with a language such as Visual Basic .NET or C#, your source code is never compiled directly into machine code. Instead, the Visual Basic or C# compiler converts your code into a special language named MSIL (Microsoft Intermediate Language). MSIL looks very much like an object-oriented assembly language. However, unlike a typical assembly language, it is not CPU specific. MSIL is a low-level and platform-independent language. When your application actually executes, the MSIL code is "just-in-time" compiled into machine code by the JITTER (the Just-In-Time compiler). Normally, your entire application is not compiled from MSIL into machine code. Instead, only the methods that are actually called during execution are compiled. In reality, the .NET Framework understands only one language: MSIL. However, you can write applications using languages such as Visual Basic .NET and C# for the

Aryan Thakur

AryansNetwork@gmail.com

.NET Framework because the .NET Framework includes compilers for these languages that enable you to compile your code into MSIL. ASP.NET ASP.NET is the umbrella term for the combination of two web development technologies: web sites and web services. Using ASP.NET, it is easier than ever to create web sites that are dynamic and data-driven, that scale well, and that work well across a broad range of browsers without any custom coding by the developer. Following are some of the significant new features of ASP.NET:

ASP.NET uses compiled code written in Common Language Runtime languages such as Visual Basic and C#. Unlike previous versions of Active Server Pages, this version does not use interpreted scripting languages such as VBScript. ASP.NET pages are built out of server-side controls. Web server controls enable you to represent and program against Hypertext Markup Language (HTML) elements using an intuitive object model. ASP.NET includes a new technology called Web Services. You can use Web Services to access methods and properties and transfer database data across the Internet. ASP.NET is part of Microsoft's .NET Framework. You can access thousands of .NET classes in your code that enable you to perform such wondrously diverse tasks as generating images on-the-fly and saving an array to a file. ASP.NET includes page and data caching mechanisms that enable you to easily and dramatically improve the performance of your Web site.

Web Server:
To test or run ASP.NET Web applications, you need a Web server. The production Web server for Microsoft operating systems is IIS, which includes a Web server, File Transfer Protocol (FTP) server, Simple Mail Transfer Protocol (SMTP) virtual e-mail server, and other facilities. In order to run IIS, you must be working with a version of Windows that is designed to function as a server in a network environment.

Aryan Thakur

AryansNetwork@gmail.com

IIS :

The Web Server, IIS, receives the request and retrieves the appropriate

ASP.Net file from disk or memory.

Understanding ASP.NET Controls ASP.NET controls are the heart of the ASP.NET Framework. An ASP.NET control is a .NET class that executes on the server and renders certain content to the browser. For example, in the first ASP.NET page created at the beginning of this chapter, a Label control was used to display the current date and time. The ASP.NET framework includes over 70 controls, which enable you to do everything from displaying a list of database records to displaying a randomly rotating banner advertisement. In this section, you are provided with an overview of the controls included in the ASP.NET Framework. You also learn how to handle events that are raised by controls and how to take advantage of View State. Overview of ASP.NET Controls The ASP.NET Framework (version 2.0) contains over 70 controls. These controls can be divided into eight groups:

Standard Controls: The standard controls enable you to render standard form elements such as buttons, input fields, and labels. We examine these controls in detail in the following chapter, "Using the Standard Controls." Validation Controls: The validation controls enable you to validate form data before you submit the data to the server. For example, you can use a RequiredFieldValidator control to check whether a user entered a value for a required input field. Rich Controls: The rich controls enable you to render things such as calendars, file upload buttons, rotating banner advertisements, and multistep wizards. Data Controls: The data controls enable you to work with data such as database data. For example, you can use these controls to submit new records to a database table or display a list of database records. Navigation Controls: The navigation controls enable you to display standard navigation elements such as menus, tree views, and bread crumb trails. Login Controls: The login controls enable you to display login, change password, and registration forms Web Part Controls: The Web Part controls enable you to build personalizable portal applications.

Aryan Thakur

AryansNetwork@gmail.com

HTML Controls: The HTML controls enable you to convert any HTML tag into a server-side control. We discuss this group of controls in the next section of this chapter.

HTML Controls
HTML controls mimic the actual HTML elements that you would use if you were using Front Page or any other HTML editor to draw your UI. You can use standard HTML elements in Web Forms, too. For example, if you wanted to create a text box, you would write: <input type="text" id=txtFirstName size=25> If you are using Visual Studio .NET, you choose a TextField control from the HTML Toolbox tab and draw the control where you want it on the HTML page. Any HTML element can be marked to also run as an HTML control when the Web Form is processed on the server by adding "runat=server" to the tag: <input type="text" id=txtFirstName size=25 runat=server> If you are using Visual Studio .NET, you can right-click the HTML element in Design View and select Run as Server Control from the context menu. HTML controls allow you to handle server events associated with the tag (a button click, for example), and manipulate the HTML tag programmatically in the Web Form code. When the control is rendered to the browser, the tag is rendered just as it is saved in the Web Form, minus the "runat=server". This gives you precise control over the HTML that is sent to the browser. Table 1. HTML controls available in ASP.NET

Control
Button

Description
A normal button that you can use to respond to Clickevents Resets all other HTML form elements on a form to a default value Automatically POSTs the form data to the specified page listed in the Action=attribute in

Web Form Code Example


<input type=button runat=server>

Reset Button

<input type=reset runat=server>

Submit Button

<input type=submit runat=server>

Aryan Thakur

AryansNetwork@gmail.com

the FORM tag Text Field Gives the user an input area <input type=text runat=server> on an HTML form Used for multi-line input on <input type=textarea runat=server> an HTML form Places a text field and <input type=file runat=server> aBrowse button on a form and allows the user to select a file name from their local machine when the Browsebutton is clicked An input area on an HTML form, although any characters typed into this field are displayed as asterisks <input type=password runat=server>

Text Area

File Field

Password Field

CheckBox

Gives the user a check box <input type=checkbox runat=server> that they can select or clear Used two or more to a <input type=radio runat=server> form, and allows the user to choose one of the controls Allows you to present information in a tabular format Displays an image on an HTML form <table runat=server></table>

Radio Button

Table

Image

<img src="FileName" runat=server>

ListBox

Displays a list of items to <select size=2 runat=server ></select> the user. You can set the size from two or more to specify how many items you wish show. If there are more items than will fit within this limit, a scroll bar is automatically added to this control.

Aryan Thakur

AryansNetwork@gmail.com

Dropdown

Displays a list of items to <select><option></option></select> the user, but only one item at a time will appear. The user can click a down arrow from the side of this control and a list of items will be displayed. Displays a horizontal line across the HTML page <hr>

Horizontal Rule

All of these controls write standard HTML into the Web Form. You may optionally assign an ID attribute to each control, allowing you to write client-side JavaScript code for any of the events that are common for this particular type of control. Below is a partial list of some of the more common client-side events. Table 2. Common client-side events

Control
OnBlur: OnChange: OnClick: OnFocus: OnMouseOver:

Description
Control loses focus Contents of the control are changed Control is clicked on Control receives focus Mouse moves over this control

Web Form Controls


Web Form controls are created and run on the Server just like the HTML controls. After performing whatever operation they are designed to do, they render the appropriate HTML and send that HTML into the output stream. For example, a DropDownList control will allow you to bind to a data source, yet the output that is rendered is standard <SELECT> and <OPTION> tags when sent to a browser. However, the sameDropDownList control might render WML if the target is a portable phone. That is why these controls do not necessarily map to any one markup language, but have the flexibility to target the appropriate markup language. All Web Form controls inherit from a common base class, namely the System.Web.UI.WebControls class. This base class implements a set of common properties that all of these controls will have. Some of these common properties are:

Aryan Thakur

AryansNetwork@gmail.com

BackColor Enabled Font ForeColor Modifiers TabIndex Visible Width

There are a few different categories of controls that are supplied by the Microsoft .NET Framework. Some controls have an almost one-to-one correspondence with their HTML counterparts. Some controls provide additional information when posted back to the server, and some controls allow you to display data in tabular or list-type format. Table 2 shows a list of Web Form server-side controls and the serverside events that you can respond to with each control. Table 2. Server-side controls used in ASP.NET and Web Forms

Control

Description

Commonly Used Server-Side Events

Web Form Code Example

Label

Displays text on the HTML page Gives the user an input area on an HTML form

None

<asp:Label id=Label1 runat="server">Label</asp:Label> <asp:TextBox id=TextBox1 runat="server"></asp:TextBox>

TextBox

TextChanged

Button

A normal button Click, Command control used to respond to click events on the server. You are allowed to pass additional information by setting the CommandName and CommandArguments properties. Like a button in that it posts back to a server, but the button looks like a hyperlink Click, Command

<asp:Button id=Button1 runat="server" Text="Button"></asp:Button>

LinkButton

<asp:LinkButton id=LinkButton1 runat="server">LinkButton</asp:LinkButton>

Aryan Thakur

AryansNetwork@gmail.com

ImageButton

Can display a Click graphical image, and when clicked, posts back to the server command information such as the mouse coordinates within the image, when clicked A normal hyperlink control that responds to a click event A normal dropdown list control like the HTML control, but can be data bound to a data source A normal ListBox control like the HTML control, but can be data bound to a data source Like a <TABLE> on steroids. You bind a data source to this control and it displays all of the column information. You can also perform paging, sorting, and formatting very easily with this control. Allows you to create a non-tabular type of format for data. You can bind the data to template items, which are like bits of None

<asp:ImageButton id=ImageButton1 runat="server"></asp:ImageButton>

Hyperlink

<asp:HyperLink id=HyperLink1 runat="server">HyperLink </asp:HyperLink>

DropDownList

SelectedIndexChanged <asp:DropDownList id=DropDownList1 runat="server"></asp:DropDownList>

ListBox

SelectedIndexChanged <asp:ListBox id=ListBox1 runat="server"></asp:ListBox>

DataGrid

CancelCommand, <asp:DataGrid id=DataGrid1 EditCommand, runat="server"></asp:DataGrid> DeleteCommand, ItemCommand, SelectedIndexChanged, PageIndexChanged, SortCommand, UpdateCommand, ItemCreated, ItemDataBound

DataList

CancelCommand, <asp:DataList id=DataList1 EditCommand, runat="server"></asp:DataList> DeleteCommand, ItemCommand, SelectedIndexChanged, UpdateCommand, 9 AryansNetwork@gmail.com

Aryan Thakur

HTML put together in a specific repeating format. Repeater

ItemCreated, ItemDataBound

Allows you to create ItemCommand, a non-tabular type of ItemCreated, format for data. You ItemDataBound can bind the data to template items, which are like bits of HTML put together in a specific repeating format. Very similar to the CheckChanged normal HTML control that displays a check box for the user to check or uncheck Displays a group of check boxes that all work together

<asp:Repeater id=Repeater1 runat="server"></asp:Repeater>

CheckBox

<asp:CheckBox id=CheckBox1 runat="server"></asp:CheckBox>

CheckBoxList

SelectedIndexChanged <asp:CheckBoxList id=CheckBoxList1 runat="server"></asp:CheckBoxList>

RadioButton

Very similar to the CheckChanged normal HTML control that displays a button for the user to check or uncheck

<asp:RadioButton id=RadioButton1 runat="server"></asp:RadioButton>

RadioButtonList Displays a group of SelectedIndexChanged <asp:RadioButtonList id=RadioButtonList1 radio button controls runat="server"></asp:RadioButtonList> that all work together Image Very similar to the None normal HTML control that displays an image within the page Used to group other controls Acts as a location None <asp:Image id=Image1 runat="server"></asp:Image>

Panel

<asp:Panel id=Panel1 runat="server">Panel</asp:Panel> <asp:PlaceHolder id="PlaceHolder1" 10 AryansNetwork@gmail.com

PlaceHolder Aryan Thakur

None

where you can dynamically add other server-side controls at run time Calendar

runat="server"></asp:PlaceHolder>

Creates an HTML SelectionChanged, <asp:Calendar id=Calendar1 version of a VisibleMonthChanged, runat="server"></asp:Calendar> calendar. You can set DayRender the default date, move forward and backward through the calendar, etc. Allows you to specify AdCreated a list of ads to display. Each time the user re-displays the page, the display rotates through the series of ads. Very similar to the None normal HTML control Used to display XML None documents within the HTML, It can also be used to perform an XSLT transform prior to displaying the XML. Like a label in that it displays a literal, but allows you to create new literals at runtime and place them into this control None <asp:AdRotator id=AdRotator1 runat="server"></asp:AdRotator>

AdRotator

Table

<asp:Table id=Table1 runat="server"></asp:Table> <asp:Xml id="Xml1" runat="server"></asp:Xml>

XML

Literal

<asp:Literal id="Literal1" runat="server"></asp:Literal>

All of these controls change their output based on the type of browser detected for the user. If the user's browser is IE, a richer look and feel can be generated using some DHTML extensions. If a down-level browser is detected (something other than IE), normal HTML 3.2 standard is sent back to the user's browser.

Aryan Thakur

11

AryansNetwork@gmail.com

Field Validator Controls


Another type of Web Form control validates data on the client browser, before the user submits the data to the back-end server. If the user fills in some data into a group of controls on an HTML page, you normally have to send all the data back to the server so it can be validated by either your ASP or ASP.NET code. Instead of having to do this round trip just to check to see if a value has been filled in, you can use one of the Field Validator controls to perform this client check. Each of these controls writes client-side JavaScript code into the HTML page so the values can be checked without the round-trip. The JavaScript works on all browsers. Table 3. Field Validator controls

Control
RequiredFieldValidator

Description
Allows you to check a control on the form to see if it is filled in with anything. If it isn't, the ErrorMessage that you set will be displayed in this control. Allows you to check the contents of one control against the contents of another control on the form to see if they match. If they don't, the ErrorMessage that you set will be displayed into this control. Allows you to check to see whether the value you entered in a control is within a specified range. If it isn't, the ErrorMessage that you set will be displayed into this 12

HTML or JavaScript Code Example


<asp:RequiredFieldValidator id=RequiredFieldValidator1 runat="server" ErrorMessage= "RequiredFieldValidator"> </asp:RequiredFieldValidator>

CompareValidator

<asp:CompareValidator id=CompareValidator1 runat="server" ErrorMessage= "CompareValidator"> </asp:CompareValidato>

RangeValidator

<asp:RangeValidator id=RangeValidator1 runat="server" ErrorMessage= "RangeValidator"> </asp:RangeValidator>

Aryan Thakur

AryansNetwork@gmail.com

control. RegularExpressionValidator Allows you to check to see if a control's contents match the input mask (regular expression) you defined. If it doesn't, the ErrorMessage that you set will be displayed into this control. Allows you to specify either a server-side or client-side script function to validate the contents of a particular control. You must return a True orFalse value from these functions. If aTrue value is returned, processing continues; if a Falsevalue is returned, the ErrorMessage specified for this control is displayed. <asp:RegularExpressionValidator id=RegularExpressionValidator1 runat="server" ErrorMessage= "RegularExpressionValidator"> </asp:RegularExpressionValidator>

CustomValidator

<asp:CustomValidator id=CustomValidator1 runat="server" ErrorMessage= "CustomValidator"> </asp:CustomValidator>

These Field Validator controls are wonderful tools for allowing you to check the user's input without a round trip back to the server.

Creating Custom Controls


In addition to the built-in controls in the .NET Framework, you can also build your own custom controls. For example, you may wish to create a menu system where each menu item is built from a database.

How Web Forms Work


Just like in Windows Forms, there are events that fire in a certain order when a Web Form initializes and loads. There are also events that fire in response to user interaction in the browser with the rendered page. When you think about how a standard ASP or HTML is created and sent to a browser, you assume

Aryan Thakur

13

AryansNetwork@gmail.com

that everything is processed in a very linear, top-down fashion. However, for a Web Form, nothing could be further from the truth. Like a Windows Form, a Web Form, goes through the standard Load, Draw (Render), and Unload types of events. Throughout this process, different procedures within the class module are called. When a page is requested from a client browser, a DLL that encapsulates both the tags in the ASPX page, as well as the page code, is loaded, then processed. First, the Init event sets the page to its initial state as described by the tags in the ASPX file. If the page is posting back to itself, Init also restores any page state that may have been stored in "viewstate". If you wish, your code can also handle the Page_Init() event to further customize the initial state of the page. Next, the Load event fires. The Load event is where you can check to see if this is the first time this page has been loaded, or whether this is a post back from the user hitting a button or other control on that page. You might perform some initialization only on the first page load, for example bind data into the controls. Next, and only if the page is posted back, control events are fired. First, all of the "change" events are fired. These events are batched up in the browser, and execute only when the page is sent back to the server. Examples include changing the text in a text box, or the selection of a list. Next, and only if the page is posted back, the control event that caused the page to post back is fired. Examples of postback events include button click, or "autopostback" change events like a check box CheckedChangedevent. Next, the page is rendered to the browser. Some state information ("viewstate") is included in a hidden field in the page so when the page is called again through a post back, ASP.NET can restore the page to its previous state. There is a final page event your code can handle before the page is disposed: Page_Unload(). Since the page is already rendered, this event is typically used to perform cleanup and logging tasks only. Finally, the class that represents the running page is disposed, and the page is unloaded from server memory. If you change the ASPX page or its code, the dynamically generated DLL that represents the page will be regenerated the next time the page is requested. This DLL is stored to disk each time it is generated.

Global.asax
The Global.asax file is similar to the Global.asa file in ASP, albeit that there are many more events available in ASP.NET. Also, Global.asax is compiled instead of interpreted as it is in ASP. You still have event procedures that fire within the Global.asax file when certain events happen on your Web site. In the following list, you will find the event procedures that are available to you within the Global.asax file. Table 4. Event procedures available within Global.asax

Aryan Thakur

14

AryansNetwork@gmail.com

Event Procedure
Application_Start Application_End Application_Error Session_Start Session_End Application_AcquireRequestState

Description
Fires when the first user hits your Web site Fires when the last user in the site's session times out Fires when an unhandled error occurs in the application Fires when any new user hits your Web site Fires when a user's session times out or ends Fires when ASP.NET acquires the current state (for example, session state) associated with the current request Fires when a security module establishes the identity of the user Fires when a security module verifies user authorization Fires when ASP.NET starts to process the request, before other per-request events Fires when ASP.NET completes the chain of execution when responding to a request Fires as the last event during the processing of the request, after other pre-request events Fires right after the ASP.NET handler (page, XML Web service) finishes execution Fires just before ASP.NET begins executing a handler such as a page or XML Web service Fires just before ASP.NET sends content to the client Fires just before ASP.NET sends HTTP headers to the client Fires after ASP.NET finishes executing all request handlers. This event causes state modules to save the 15 AryansNetwork@gmail.com

Application_AuthenticateRequest

Application_AuthorizeRequest Application_BeginRequest

Application_Disposed

Application_EndRequest

Application_PostRequestHandlerExecute

Application_PreRequestHandlerExecute

Application_PreSendRequestContent Application_PreSendRequestHeaders

Application_ReleaseRequestState

Aryan Thakur

current state data Application_ResolveRequestCache Fires after ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the handler (the page or Web service, for example). Fires after ASP.NET finishes executing a handler in order to let caching modules store responses that will be used to serve subsequent requests from the cache

Application_UpdateRequestCache

Create a Web Form


Let's create a Web Form that allows a user to input their first and last names. After entering the data into these two text fields on the Web page, the user clicks a login button and the user's Last name, First name appear in a label below the login button. Figure 2 shows the sample login Web Form that you will use.

Figure 2: Sample showing how to enter data and display it back into a label control To build a Login form

Aryan Thakur

16

AryansNetwork@gmail.com

1. 2. 3. 4. 5. 6. 7. 8.

Open Visual Studio and, on the Start page, click Create New Project. Highlight Visual Basic Projects from the treeview on the left. In the Templates window, click Web Application. For the Name of this project, type WebForms101. Choose the location of the machine where you wish to create this Web site. Click OK to begin the process of creating the new Web Application project. You should now have a Web Form named WebForm1.aspx in your Visual Studio project. Rename this form to Login.aspx. Open the Toolbox and create the form in Figure 3 by adding the appropriate controls and setting the properties of those controls as outlined in Table 5. Table 5. Controls used to build the Login form

Control Type
Label

Property
Name Text

Value
Label1 First Name txtFirst

TextBox

Name Text

Label

Name Text

Label2 Last Name txtLast

TextBox

Name Text

Button

Name Text

btnSubmit Login lblName Insert

Label

Name BorderStyle Text

Try It Out

Aryan Thakur

17

AryansNetwork@gmail.com

At this point, you can run this application and see this Web Form appear in your browser. Although this page does not have any functionality yet, this exercise is a good test to make sure everything is running up to this point. 1. 2. Press F5 to run this sample application. If you receive an error message informing you that you need a start page, right-click the Login.aspx page and click Set as Start Page from the context menu.

You should now see the Web Form displayed in your browser, and you can enter data into the two text fields. If you click the Login button, nothing will happen because you have not told it to do anything yet. You will next learn how to make this Login button do something.

Adding Code to the Button


Let's add some code to the button so that it posts the data you entered in the text boxes, and fills in the appropriate data in the label below the button control. 1. 2. 3. End the program by closing down the browser. While looking at the Login page in design mode, double-click the Login button control. You will now see a code window appear with the event procedure btnSubmit. Right-click by your cursor. Fill in the Click event procedure so it looks like the following code.
1. protected void btnSubmit_Click(object sender, EventArgs e) 2. { lblName.Text=txtLast.Text+,+txtFist.Text; 3. }

What you have just done is retrieved the text property from both the txtLast and txtFirst text boxes and placed the data into the label control below the Login button. This should look very familiar, if you have ever programmed in Visual Basic. In fact, the whole point of .NET is that all of the coding, whether for Windows applications or Web applications, should look the same.

Aryan Thakur

18

AryansNetwork@gmail.com

Вам также может понравиться