Sie sind auf Seite 1von 17

Introduction to ASP.

NET
What is an ASP File? An ASP file is just the same as an HTML file An ASP file can contain text, HTML, XML, and scripts Scripts in an ASP file are executed on the server An ASP file has the file extension ".asp" What is ASP .NET? ASP.NET is the latest version of ASP. ASP .NET is the next generation ASP, but it's not an upgraded version of ASP. ASP .NET is an entirely new paradigm for server-side ASP scripting. ASP .NET is a part of the new .NET (dotnet) Framework. An ASP.NET file has the file extension ".aspx" .NET Framework The .NET Framework is the infrastructure for the Microsoft .NET Platform. The .NET Framework is a common environment for building, deploying, and running Web applications and Web Services. The .NET Framework contains a common language runtime and common class libraries - like ADO .NET, ASP .NET and Windows Forms - to provide advanced standard services that can be integrated into a variety of computer systems. The .NET Framework provides a feature-rich application environment, simplified development and easy integration between a number of different development languages. The .NET Framework is language neutral. Currently it supports C++, C#, Visual Basic, and JScript (The Microsoft version of JavaScript).

New in ASP .NET


Better Language Support Programmable Controls Event Driven Programming XML Based Components User Authentication, with Accounts and Roles Higher Scalability Increased Performance - Compiled Code Easier Configuration and Deployment Not Fully ASP Compatible

Language Support

ASP .NET uses the new ADO .NET. ASP .NET supports full Visual Basic, not VBScript like ASP. ASP .NET supports C# (C sharp) and C++. ASP .NET supports JScript as before

Difference Between HTML, ASP, and ASP.NET A static ASP or ASP.NET page is no different from an HTML only difference is the way the files are saved: .htm, .asp, or .aspx extensions. The codes below could be saved as an HTML. ASP, or ASP.NET page, giving the same result. View this page as an HTML, ASP, or an ASP.NET page. For dynamic effect, we need to program the Web pages behind the scene thats where the ASP and ASP.NET come into picture. For example, one can create a Web page to work as a Form for data input; however without programming, the data do not go anywhere not saved, nor printed, or anything.
<html> <head> <title>Inserting ASP.NET code Example</title> </head> <body> Line1: First HTML Line<br /> Line2: Second HTML Line<br /> Line3: Third HTML Line<br /> </body> </html> 2

New ASP.NET Resources The two main types of Web resources created with ASP.NET applications are WebForms and Web Services. WebForms: WebForms allow you to quickly develop and process forms on Web pages, and develop cross-browser Web applications. WebForms are Web pages that are identified with the file extension .aspx. An example is a shopping cart. Web Services: Web Services are ASP.NET Web pages that contain publicly exposed code so that other applications can interact with them. Web Services are identified with the file extension .asmx. A company could, for example, expose the product ordering functionality of their Web site in order to allow other Web sites to connect to this function. For each sale that originated from other Web sites, the company could pay a referral fee.

WebForms WebForms are ASP.NET pages within an ASP.NET application. In previous versions of ASP, HTML is intermixed with ASP code within the same script. The ASP.NET WebForm is separated into two logical areas, the HTML template and a collection of code behind the WebForm. The HTML template usually contains the design layout, content, and the controls. The HTML template is created using a combination of HTML controls and server controls. HTML Controls HTML Controls are typically found on a Web page that include buttons, textboxes, checkboxes, and dropdown lists. These controls are understood by the browsers. Users typically use these controls to send information from a browser to a Web server using another file or program. For example: <input type=radio value=Yes/> Yes Server Controls Server controls are tags understood by the Web server. There are several types of server controls: HTML Server Controls, ASP.NET Form Controls, Data Validation controls, User Controls, Mobile controls, and Literal controls. Appendix A contains some sets of server controls. HTML Server Controls: HTML Server controls are similar to the HTML controls, except they are processed by the server. Using HTML Server controls, you only need to write runat = "server" to the HTML control to transform it into an HTML Server control. By transforming HTML controls to HTML Server controls, you can create server-side programs that can interact with the control before it is rendered as a plain HTML control and sent to the browser. Below is a sample of an HTML Server control. For example: <input type=radio runat=server value=Yes/> Yes

ASP.NET Form Controls: ASP controls are usually identified with the prefix asp: followed by the name of the control. For example, the control for an ASP.NET button is written as:
<asp:Button id="ShowBtn" runat="server" Text="Show the message." />.

ASP.NET form controls allow you to create controls that render HTML output and that provide more flexibility when you are creating your programs. ASP.NET form controls can interact with client-side events, such as when the user clicks on a button. When the event occurs, ASP.NET can trigger a script to run on the server. Data Validation Controls: Data Validation controls validate form data without extensive JavaScript programming. User Controls: User controls are external files that can be included within another WebForm. User controls allow you to reuse code across multiple files. User controls are often used for creating self-contained code, headers, menus, and footers. User controls replace the functionality of ASP server-side include pages. User controls are identified with the file extension .asmx. Mobile controls: Mobile controls are a series of controls that provide form functionality within wireless and mobile devices. The rendering of the user interface occurs automatically, depending upon which device is used. Literal Controls: LiteralControls are page content that is not assigned to a specific HTML control. For example, any text sent to the browser is a Literalcontrol. Literal controls can be used to send a combination of HTML tags and text to the browser.

The Code Behind the Page With WebForms, the server programs are written in a separate file known as the code behind the page. Only Server controls can interact with the code behind the page. The code behind the page may be written in any ASP.NET compatible language such as Visual Basic.NET, C#, Perl, or Java. Naming the code behind the page: The code behind the page has the same filename as the WebForm. However, the file extension will vary with the programming language used. The filename for the code behind the page has the extension .vb if the code is written in Visual Basic.NET. If the page is written in C#, the file has the extension .cs. The location of the code behind the page is determined via a property that is set on the first line in the page using the @Page directive. Identifying the code behind the page from the HTML Template: This code is written on the first line in the HTML template. The @Page directive allows you to set the default properties for the entire page. The CodeBehind property indicates the file where the code is located. The Inherits property indicates the class that the page inherits. <%@ Page Language="vb" Codebehind="WebForm1.vb" Inherits="TaraStore.WebForm1"%> The compiled class code: The compiled code behind the page is the class definition for the page. A class is a named logical grouping of code. The class definition contains the functions, methods, and properties that belong to that class. In Visual Studio.NET the process of compiling a class is called building. When you build the application, you compile the code into an executable file.

Visual Studio.NET compiles the code behind the page into an executable file and places the file in the bin directory. Postback When a user fills out a form and clicks the Submit button, the data is sent to the Web server. It is helpful to redisplay the values that the user entered. To maintain this information across browser requests is known as maintaining state. The process of posting data back to a form is known as postback. A hidden form field named _ViewState is a very long string that contains information required to maintain the form data across multiple page requests. This encoded string is decoded by the Web Server. Therefore, the value of _ViewState changes each time the form is reposted back to the server. Page Class All Web pages created by ASP.NET are originated from a object class called Page. The Page class contains other object classes. The Page class also has a variety of events/methods, functions, and properties that can be accessed from within the code behind the page. Page Class Events The first time a page is requested by a client, a series of page events occurs. Page_Init event is the first page event and initializes the page control hierarchy.

Page_Load event loads any server controls into memory and occurs every time the page is executed. In the following sample code, a message is displayed when the Page_Load event occurs. Sub Page_Load(s As Object, e As EventArgs) Message.InnerHtml = "Welcome!" End Sub

Not

In Visual Basic.NET, the event handler is known as a procedure. When you create a procedure, you must identify the beginning of the procedure with the keyword Sub, and the ending with the keywords End Sub. You also need to indicate if any values known as parameters are passed to the procedures.

Server control events can be action events, such as the click event for a server button control, or change events, such as when the value of a server text control changes. In the following sample code, the page contains an HTML server button control named MyBtn and a span tag named Message.
<script language="VB" runat="server"> Sub MyBtn_Click(s As Object, E as EventArgs) Message.InnerHtml = "You clicked me!" End Sub </script> <HTML><HEAD><TITLE>Server Control Event Sample</TITLE></HEAD> <BODY> <button id="MyBtn" runat="server" OnServerClick="MyBtn_Click"> Click me! </button> <h1><span id="Message" runat=server/></h1> </BODY> </HTML>

Page_CommittTransaction and Page_AbortTransaction are used in combination to define a sequential series of events which together are called a transaction. In a transaction, all events must occur; otherwise all events are rolled back to their original state. Page_PreRender event occurs immediately before the control hierarchy is rendered and sent to the browser. Page_Unload event occurs and the page is removed from the servers memory Sub Page_UnLoad(s As Object, e As EventArgs)
8

Message.InnerHtml = "Goodbye!" End Sub Built-in ASP.NET Objects ASP.NET pages have access to objects that are built into the Web Server, along with their properties and methods. You can access built-in ASP.NET objects in the code behind the page. The following is a list of some of these built-in objects.

RequestUsed to access information that is passed from the clients browser to the Web server. For example, the Request object is used to retrieve information that a user filled in a form. ResponseUsed to send information from the Web server to the clients browser. For example, the Response object is used to redirect the user to another Web page. SessionUsed to share information between a single client and the Web server. ApplicationAllows developers to treat a sequence of Web pages as a single application, which means that information, such as the name of the application or the total number of visitors on the Web site, can be shared among all the users of an ASP application.

The Request Object (Page Request Property): The Request object is directly mapped to the Request property of the Page object. Thus data for the Request object can be directly accessed from the methods and properties of the Page object. The Page Request property allows a user to retrieve any information sent by the browser to Web server in the TCP/IP header. When a browser sends a request for a Web page to the Web server, the Web server receives the request and some additional information in the TCP/IP header. The TCP/IP header includes the date and time, the type of request (get or post), the page requested, the HTTP version, the default language, the
9

referring page, the IP address of the client, the cookies associated with that domain, and the user agent. For example: Response.Write(Request.PhysicalPath) the physical path to the file Response.Write (Request.UserHostAddress) IP address of the server The Request property also provides access to the form fields and values of a Web page. If the form method is GET, then the form field-value pairs are sent to the Web server through a QueryString appended to the url of the WEb server. For example: http://www.tarastore.com/index.asp?name=katie&topic=asp Here & separates the name-value pairs and = separates the name and value. QueryString.Form Sample: The sample code below creates a text box named password and a button named MyBtn, and displays the password when the button is clicked.
<script language="VB" runat="server"> Sub MyBtn_Click(s As Object, E as EventArgs) Response.write(Request.QueryString("PWD")) End Sub </script> <HTML><HEAD><TITLE>Server Control Event Sample</TITLE></HEAD> <BODY> <span id="Message" runat="server"> Please enter your password</span> <form method= GET action = QueryStringSample.aspx runat="server" <input id="PWD" type="password" size="8" runat="server"> <br /> <input id="MyBtn" type="submit" value="Login" OnServerClick="MyBtn_Click" runat="server"> </FORM> </BODY></HTML>
10

Request.Form Sample: If the form method is POST, it is sent as part of the HTTP request body. The page uses the Request property to retrieve information from the form field and displays the value.
<script language="VB" runat="server"> Sub MyBtn_Click(s As Object, E as EventArgs) Response.write(Request.Form("PWD")) End Sub </script> <HTML><HEAD><TITLE>Server Control Event Sample</TITLE></HEAD> <BODY> <span id="Message" runat="server"> Please enter your password</span> <form method= POST action = QueryStringSample.aspx runat="server" <input id="PWD" type="password" size="8" runat="server"> <br /> <input id="MyBtn" type="submit" value="Login" OnServerClick="MyBtn_Click" runat="server"> </FORM> </BODY></HTML>

Direct Access of Values and Properties of Form Field Elements: A simpler method to retrieve the value from a form field is to directly access the value properties of the form field. The property name that you use to access the value is different with each type of server control. However, this method only works with server controls. So, you dont need the action or method properties for the form, only set the runat property to server. For example:
<script language="VB" runat="server"> Sub MyBtn_Click(s As Object, E as EventArgs) Response.write(PWD.value) End Sub </script> <HTML><HEAD><TITLE>Server Control Event Sample</TITLE></HEAD> <BODY> <span id="Message" runat="server"> Please enter your password</span> <form runat="server"> <input id="PWD" type="password" size="8" runat="server"> <br /> <input id="MyBtn" type="submit" value="Login" OnServerClick="MyBtn_Click" runat="server"> </FORM> </BODY></HTML>

11

The Response Object (Page Response Property): The Response object is used to send information to the browser. Cookies collection is used to send cookies to the browser. The Response object is directly mapped to the Response property of the Page object. Thus data for the Response object can be directly accessed from the methods and properties of the Page object.The Response object has several methods, such as Write, WriteFile, and Redirect. The write method allows you to send a string to the browser as text, HTML and client-script. You can use a variable or expression to store the string: Response.Write("Copyright by TaraStore<br/>") or Dim strMessage as String = "Copyright by TaraStore<br/>") Response.Write(strMessage) WriteFile method is also used to write the entire contents of a file to the Web page: Response.WriteFile("c:\copyright.txt") Redirect method allows you to redirect the browser to another page. Because this redirection occurs on the server, the visitor never knows that they have been redirected to a new page. Response.Redirect("http://www.course.com/")

12

Web Services Methods to integrate data into your Web site from other applications: Post a link with the query that sends the user to the Web page. Scrape a Web site to capture the source code. Use costly integrated custom applications that are often not reusable Use a Web Service application Web Services are used to create business to business applications. Web Services allow you to expose part or all of your programs over the Internet. Web Services is built using Open Standards; Web Services are supported across applications and platforms.

13

APPENDIX A: ASP.NET Server Controls


There are mainly three kinds of server controls: HTML Server Controls Traditional HTML tags, Web Server Controls - New ASP .NET tags, and Validation Server Controls - For input validation.

HTML Server Controls


HTML server controls are HTML tags understood by the server. HTML elements in ASP .NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. Note: All HTML server controls must be within a <form> tag with the runat="server" attribute! Note: ASP .NET requires that all HTML elements must be properly closed and properly nested.
HTML Server Control HtmlAnchor HtmlButton HtmlForm HtmlGeneric HtmlImage HtmlInputButton HtmlInputCheckBox HtmlInputFile HtmlInputHidden HtmlInputImage HtmlInputRadioButton HtmlInputText HtmlSelect HtmlTable HtmlTableCell HtmlTableRow HtmlTextArea Description Controls an <a> HTML element Controls a <button> HTML element Controls a <form> HTML element Controls other HTML element not specified by a specific HTML server control, like <body>, <div>, <span>, etc. Controls an <image> HTML element Controls <input type="button">, <input type="submit">, and <input type="reset"> HTML elements Controls an <input type="checkbox"> HTML element Controls an <input type="file"> HTML element Controls an <input type="hidden"> HTML element Controls an <input type="image"> HTML element Controls an <input type="radio"> HTML element Controls <input type="text"> and <input type="password"> HTML elements Controls a <select> HTML element Controls a <table> HTML element Controls <td>and <th> HTML elements Controls a <tr> HTML element Controls a <textarea> HTML element

14

Web Server Controls


Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more complex elements. The syntax for creating a Web server control is:

<asp:control_name id="some_id" runat="server" />

Web Server Control AdRotator Button Calendar CheckBox CheckBoxList DataGrid DataList DropDownList HyperLink Image ImageButton Label LinkButton ListBox Literal Panel PlaceHolder RadioButton RadioButtonList Repeater Table TableCell TableRow TextBox Xml

Description Displays a sequence of images Displays a push button Displays a calendar Displays a check box Creates a multi-selection check box group Displays fields of a data source in a grid Displays items from a data source by using templates Creates a drop-down list Creates a hyperlink Displays an image Displays a clickable image Displays static content which is programmable (lets you apply styles to its content) Creates a hyperlink button Creates a single- or multi-selection drop-down list Displays static content which is programmable (does not let you apply styles to its content) Provides a container for other controls Reserves space for controls added by code Creates a radio button Creates a group of radio buttons Displays a repeated list of items bound to the control Creates a table Creates a table cell Creates a table row Creates a text box Displays an XML file or the results of an XSL transform

15

An Example of HTML Server Control:


In the following example we declare an HtmlAnchor server control in an .aspx file. Then we set the href attribute of the HtmlAnchor control in an event handler (an event handler is a subroutine that executes code for a given event). The Page_Load event is one of many events that ASP .NET understands. The executable code itself has been moved outside the HTML.

<script runat="server"> Sub Page_Load link1.HRef="http://www.cl.uh.edu" End Sub </script> <html> <body> <form runat="server"> <a id="link1" runat="server">Visit UHCL</a> </form> </body> </html>

An Example of ASP Server Control:


In the following example we declare a Button server control in an .aspx file. Then we create an event handler for the Click event which changes the text on the button.

<script runat="server"> Sub submit(Source As Object, e As EventArgs) button1.Text="You clicked me!" End Sub </script> <html> <body> <form runat="server"> <asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit"/> </form> </body> </html>

16

Validation Server Controls


A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the user. Each validation control performs a specific type of validation (like validating against a specific value or a range of values). By default, page validation is performed when a Button, ImageButton, or LinkButton control is clicked. You can prevent validation when a button control is clicked by setting the CausesValidation property to false. The syntax for creating a Validation server control is:
<asp:control_name id="some_id" runat="server" />
Validation Server Control CompareValidator CustomValidator RangeValidator RegularExpressionValidator RequiredFieldValidator ValidationSummary Description Compares the value of one input control to the value of another input control or to a fixed value Allows you to write a method to handle the validation of the value entered Checks that the user enters a value that falls between two values Ensures that the value of an input control matches a specified pattern Makes an input control a required field Displays a report of all validation errors occurred in a Web page

In the following example we declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator control:
<html> <body> <form runat="server"> Enter a number from 1 to 100: <asp:TextBox id="tbox1" runat="server" /><br /><br /> <asp:Button Text="Submit" runat="server" /><br /> <asp:RangeValidator ControlToValidate="tbox1" MinimumValue="1" MaximumValue="100" Type="Integer" EnableClientScript="false" Text="The value must be from 1 to 100!" runat="server" /> </form> </body> </html>

17

Das könnte Ihnen auch gefallen