ASP.NET Tutorial PDF Version Quick Guide Resources Job Search Discussion ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily. This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started. Audience This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc Print Page Previous Next Advertisements ”;
Category: asp.net
ASP.NET – HTML Server
ASP.NET – HTML Server ”; Previous Next The HTML server controls are basically the standard HTML controls enhanced to enable server side processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are sent to the browser for display. They are specifically converted to a server control by adding the attribute runat=”server” and adding an id attribute to make them available for server-side processing. For example, consider the HTML input control: <input type=”text” size=”40″> It could be converted to a server control, by adding the runat and id attribute: <input type=”text” id=”testtext” size=”40″ runat=”server”> Advantages of using HTML Server Controls Although ASP.NET server controls can perform every job accomplished by the HTML server controls, the later controls are useful in the following cases: Using static tables for layout purposes. Converting a HTML page to run under ASP.NET The following table describes the HTML server controls: Control Name HTML tag HtmlHead <head>element HtmlInputButton <input type=button|submit|reset> HtmlInputCheckbox <input type=checkbox> HtmlInputFile <input type = file> HtmlInputHidden <input type = hidden> HtmlInputImage <input type = image> HtmlInputPassword <input type = password> HtmlInputRadioButton <input type = radio> HtmlInputReset <input type = reset> HtmlText <input type = text|password> HtmlImage <img> element HtmlLink <link> element HtmlAnchor <a> element HtmlButton <button> element HtmlButton <button> element HtmlForm <form> element HtmlTable <table> element HtmlTableCell <td> and <th> HtmlTableRow <tr> element HtmlTitle <title> element HtmlSelect <select&t; element HtmlGenericControl All HTML controls not listed Example The following example uses a basic HTML table for layout. It uses some boxes for getting input from the users such as name, address, city, state etc. It also has a button control, which is clicked to get the user data displayed in the last row of the table. The page should look like this in the design view: The code for the content page shows the use of the HTML table element for layout. <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”htmlserver._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Untitled Page</title> <style type=”text/css”> .style1 { width: 156px; } .style2 { width: 332px; } </style> </head> <body> <form id=”form1″ runat=”server”> <div> <table style=”width: 54%;”> <tr> <td class=”style1″>Name:</td> <td class=”style2″> <asp:TextBox ID=”txtname” runat=”server” style=”width:230px”> </asp:TextBox> </td> </tr> <tr> <td class=”style1″>Street</td> <td class=”style2″> <asp:TextBox ID=”txtstreet” runat=”server” style=”width:230px”> </asp:TextBox> </td> </tr> <tr> <td class=”style1″>City</td> <td class=”style2″> <asp:TextBox ID=”txtcity” runat=”server” style=”width:230px”> </asp:TextBox> </td> </tr> <tr> <td class=”style1″>State</td> <td class=”style2″> <asp:TextBox ID=”txtstate” runat=”server” style=”width:230px”> </asp:TextBox> </td> </tr> <tr> <td class=”style1″> </td> <td class=”style2″></td> </tr> <tr> <td class=”style1″></td> <td ID=”displayrow” runat =”server” class=”style2″> </td> </tr> </table> </div> <asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Click” /> </form> </body> </html> The code behind the button control: protected void Button1_Click(object sender, EventArgs e) { string str = “”; str += txtname.Text + “<br />”; str += txtstreet.Text + “<br />”; str += txtcity.Text + “<br />”; str += txtstate.Text + “<br />”; displayrow.InnerHtml = str; } Observe the following: The standard HTML tags have been used for the page layout. The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it. Print Page Previous Next Advertisements ”;
ASP.NET – Error Handling
ASP.NET – Error Handling ”; Previous Next Error handling in ASP.NET has three aspects: Tracing – tracing the program execution at page level or application level. Error handling – handling standard errors or custom errors at page level or application level. Debugging – stepping through the program, setting break points to analyze the code In this chapter, we will discuss tracing and error handling and in this chapter, we will discuss debugging. To understand the concepts, create the following sample application. It has a label control, a dropdown list, and a link. The dropdown list loads an array list of famous quotes and the selected quote is shown in the label below. It also has a hyperlink which has points to a nonexistent link. <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”errorhandling._Default” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Tracing, debugging and error handling </title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:Label ID=”lblheading” runat=”server” Text=”Tracing, Debuggin and Error Handling”> </asp:Label> <br /> <br /> <asp:DropDownList ID=”ddlquotes” runat=”server” AutoPostBack=”True” onselectedindexchanged=”ddlquotes_SelectedIndexChanged”> </asp:DropDownList> <br /> <br /> <asp:Label ID=”lblquotes” runat=”server”> </asp:Label> <br /> <br /> <asp:HyperLink ID=”HyperLink1″ runat=”server” NavigateUrl=”mylink.htm”>Link to:</asp:HyperLink> </div> </form> </body> </html> The code behind file: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string[,] quotes = { {“Imagination is more important than Knowledge.”, “Albert Einsten”}, {“Assume a virtue, if you have it not” “Shakespeare”}, {“A man cannot be comfortable without his own approval”, “Mark Twain”}, {“Beware the young doctor and the old barber”, “Benjamin Franklin”}, {“Whatever begun in anger ends in shame”, “Benjamin Franklin”} }; for (int i=0; i<quotes.GetLength(0); i++) ddlquotes.Items.Add(new ListItem(quotes[i,0], quotes[i,1])); } } protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e) { if (ddlquotes.SelectedIndex != -1) { lblquotes.Text = String.Format(“{0}, Quote: {1}”, ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue); } } } Tracing To enable page level tracing, you need to modify the Page directive and add a Trace attribute as shown: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”errorhandling._Default” Trace =”true” %> Now when you execute the file, you get the tracing information: It provides the following information at the top: Session ID Status Code Time of Request Type of Request Request and Response Encoding The status code sent from the server, each time the page is requested shows the name and time of error if any. The following table shows the common HTTP status codes: Number Description Informational (100 – 199) 100 Continue 101 Switching protocols Successful (200 – 299) 200 OK 204 No content Redirection (300 – 399) 301 Moved permanently 305 Use proxy 307 Temporary redirect Client Errors (400 – 499) 400 Bad request 402 Payment required 404 Not found 408 Request timeout 417 Expectation failed Server Errors (500 – 599) 500 Internal server error 503 Service unavailable 505 HTTP version not supported Under the top level information, there is Trace log, which provides details of page life cycle. It provides elapsed time in seconds since the page was initialized. The next section is control tree, which lists all controls on the page in a hierarchical manner: Last in the Session and Application state summaries, cookies, and headers collections followed by list of all server variables. The Trace object allows you to add custom information to the trace output. It has two methods to accomplish this: the Write method and the Warn method. Change the Page_Load event handler to check the Write method: protected void Page_Load(object sender, EventArgs e) { Trace.Write(“Page Load”); if (!IsPostBack) { Trace.Write(“Not Post Back, Page Load”); string[,] quotes = ………………….. } } Run to observe the effects: To check the Warn method, let us forcibly enter some erroneous code in the selected index changed event handler: try { int a = 0; int b = 9 / a; }catch (Exception e) { Trace.Warn(“UserAction”, “processing 9/a”, e); } Try-Catch is a C# programming construct. The try block holds any code that may or may not produce error and the catch block catches the error. When the program is run, it sends the warning in the trace log. Application level tracing applies to all the pages in the web site. It is implemented by putting the following code lines in the web.config file: <system.web> <trace enabled=”true” /> </system.web> Error Handling Although ASP.NET can detect all runtime errors, still some subtle errors may still be there. Observing the errors by tracing is meant for the developers, not for the users. Hence, to intercept such occurrence, you can add error handing settings in the web.config file of the application. It is application-wide error handling. For example, you can add the following lines in the web.config file: <configuration> <system.web> <customErrors mode=”RemoteOnly” defaultRedirect=”GenericErrorPage.htm”> <error statusCode=”403″ redirect=”NoAccess.htm” /> <error statusCode=”404″ redirect=”FileNotFound.htm” /> </customErrors> </system.web> <configuration> The <customErrors> section has the possible attributes: Mode : It enables or disables custom error pages. It has the three possible values: On : displays the custom pages. Off : displays ASP.NET error pages (yellow pages) remoteOnly : It displays custom errors to client, display ASP.NET errors locally. defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors. To put different custom error pages for different type of errors, the <error> sub tags are used, where different error pages are specified, based on the status code of the errors. To implement page level error handling, the Page directive could be modified: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”errorhandling._Default” Trace =”true” ErrorPage=”PageError.htm” %> Because ASP.NET Debugging is an important subject in itself, so we would discuss it in the next chapter separately. Print Page Previous Next Advertisements ”;
ASP.NET – Server Side
ASP.NET – Server Side ”; Previous Next We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following extremely useful properties that correspond to intrinsic objects: Session Application Cache Request Response Server User Trace We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs. Properties and Methods of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. The following table provides a list of the properties: Property Description MachineName Name of server computer ScriptTimeOut Gets and sets the request time-out value in seconds. The following table provides a list of some important methods: Method Description CreateObject(String) Creates an instance of the COM object identified by its ProgID (Programmatic ID). CreateObject(Type) Creates an instance of the COM object identified by its Type. Equals(Object) Determines whether the specified Object is equal to the current Object. Execute(String) Executes the handler for the specified virtual path in the context of the current request. Execute(String, Boolean) Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections. GetLastError Returns the previous exception. GetType Gets the Type of the current instance. HtmlEncode Changes an ordinary string into a string with legal HTML characters. HtmlDecode Converts an Html string into an ordinary string. ToString Returns a String that represents the current Object. Transfer(String) For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page. UrlDecode Converts an URL string into an ordinary string. UrlEncodeToken Works same as UrlEncode, but on a byte array that contains Base64-encoded data. UrlDecodeToken Works same as UrlDecode, but on a byte array that contains Base64-encoded data. MapPath Return the physical path that corresponds to a specified virtual file path on the server. Transfer Transfers execution to another web page in the current application. Request Object The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser. The information presented by this object is wrapped by the higher level abstractions (the web control model). However, this object helps in checking some information such as the client browser and cookies. Properties and Methods of the Request Object The following table provides some noteworthy properties of the Request object: Property Description AcceptTypes Gets a string array of client-supported MIME accept types. ApplicationPath Gets the ASP.NET application”s virtual application root path on the server. Browser Gets or sets information about the requesting client”s browser capabilities. ContentEncoding Gets or sets the character set of the entity-body. ContentLength Specifies the length, in bytes, of content sent by the client. ContentType Gets or sets the MIME content type of the incoming request. Cookies Gets a collection of cookies sent by the client. FilePath Gets the virtual path of the current request. Files Gets the collection of files uploaded by the client, in multipart MIME format. Form Gets a collection of form variables. Headers Gets a collection of HTTP headers. HttpMethod Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client. InputStream Gets the contents of the incoming HTTP entity body. IsSecureConnection Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS). QueryString Gets the collection of HTTP query string variables. RawUrl Gets the raw URL of the current request. RequestType Gets or sets the HTTP data transfer method (GET or POST) used by the client. ServerVariables Gets a collection of Web server variables. TotalBytes Gets the number of bytes in the current input stream. Url Gets information about the URL of the current request. UrlReferrer Gets information about the URL of the client”s previous request that is linked to the current URL. UserAgent Gets the raw user agent string of the client browser. UserHostAddress Gets the IP host address of the remote client. UserHostName Gets the DNS name of the remote client. UserLanguages Gets a sorted string array of client language preferences. The following table provides a list of some important methods: Method Description BinaryRead Performs a binary read of a specified number of bytes from the current input stream. Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from object.) GetType Gets the Type of the current instance. MapImageCoordinates Maps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values. MapPath(String) Maps the specified virtual path to a physical path. SaveAs Saves an HTTP request to disk. ToString Returns a String that represents the current object. ValidateInput Causes validation to occur for the collections accessed through the Cookies, Form, and QueryString properties. Response Object The Response object represents the server”s response to the client request. It is an instance of the System.Web.HttpResponse class. In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves. However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip. Properties and Methods of the Response Object The following table provides some noteworthy properties of the Response object: Property Description Buffer Gets or sets a value indicating whether to buffer the output and send it after the complete response is finished processing. BufferOutput Gets or sets a value
ASP.NET – File Uploading
ASP.NET – File Uploading ”; Previous Next ASP.NET has two controls that allow users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it, or ignore it. The following controls allow the file uploading: HtmlInputFile – an HTML server control FileUpload – and ASP.NET web control Both controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so. In this tutorial, we use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a browse button and a text box for entering the filename. Once, the user has entered the filename in the text box by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk. The basic syntax of FileUpload is: <asp:FileUpload ID= “Uploader” runat = “server” /> The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties: Properties Description FileBytes Returns an array of the bytes in a file to be uploaded. FileContent Returns the stream object pointing to the file to be uploaded. FileName Returns the name of the file to be uploaded. HasFile Specifies whether the control has a file to upload. PostedFile Returns a reference to the uploaded file. The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class. The HttpPostedFile class has the following frequently used properties: Properties Description ContentLength Returns the size of the uploaded file in bytes. ContentType Returns the MIME type of the uploaded file. FileName Returns the full filename. InputStream Returns a stream object pointing to the uploaded file. Example The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type, and file length. In the design view, the form looks as follows: The content file code is as given: <body> <form id=”form1″ runat=”server”> <div> <h3> File Upload:</h3> <br /> <asp:FileUpload ID=”FileUpload1″ runat=”server” /> <br /><br /> <asp:Button ID=”btnsave” runat=”server” onclick=”btnsave_Click” Text=”Save” style=”width:85px” /> <br /><br /> <asp:Label ID=”lblmessage” runat=”server” /> </div> </form> </body> The code behind the save button is as given: protected void btnsave_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); if (FileUpload1.HasFile) { try { sb.AppendFormat(” Uploading file: {0}”, FileUpload1.FileName); //saving the file FileUpload1.SaveAs(“<c:\SaveDirectory>” + FileUpload1.FileName); //Showing the file information sb.AppendFormat(“<br/> Save As: {0}”, FileUpload1.PostedFile.FileName); sb.AppendFormat(“<br/> File type: {0}”, FileUpload1.PostedFile.ContentType); sb.AppendFormat(“<br/> File length: {0}”, FileUpload1.PostedFile.ContentLength); sb.AppendFormat(“<br/> File name: {0}”, FileUpload1.PostedFile.FileName); }catch (Exception ex) { sb.Append(“<br/> Error <br/>”); sb.AppendFormat(“Unable to save file <br/> {0}”, ex.Message); } } else { lblmessage.Text = sb.ToString(); } } Note the following: The StringBuilder class is derived from System.IO namespace, so it needs to be included. The try and catch blocks are used for catching errors, and display the error message. Print Page Previous Next Advertisements ”;
ASP.NET – Validators
ASP.NET – Validators ”; Previous Next ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or contradictory data don”t get stored. ASP.NET provides the following validation controls: RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary BaseValidator Class The validation control classes are inherited from the BaseValidator class hence they inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls: Members Description ControlToValidate Indicates the input control to validate. Display Indicates how the error message is shown. EnableClientScript Indicates whether client side validation will take. Enabled Enables or disables the validator. ErrorMessage Indicates error string. Text Error text to be shown if validation fails. IsValid Indicates whether the value of the control is valid. SetFocusOnError It indicates whether in case of an invalid control, the focus should switch to the related input control. ValidationGroup The logical group of multiple validators, where this control belongs. Validate() This method revalidates the control and updates the IsValid property. RequiredFieldValidator Control The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box. The syntax of the control is as given: <asp:RequiredFieldValidator ID=”rfvcandidate” runat=”server” ControlToValidate =”ddlcandidate” ErrorMessage=”Please choose a candidate” InitialValue=”Please choose a candidate”> </asp:RequiredFieldValidator> RangeValidator Control The RangeValidator control verifies that the input value falls within a predetermined range. It has three specific properties: Properties Description Type It defines the type of the data. The available values are: Currency, Date, Double, Integer, and String. MinimumValue It specifies the minimum value of the range. MaximumValue It specifies the maximum value of the range. The syntax of the control is as given: <asp:RangeValidator ID=”rvclass” runat=”server” ControlToValidate=”txtclass” ErrorMessage=”Enter your class (6 – 12)” MaximumValue=”12″ MinimumValue=”6″ Type=”Integer”> </asp:RangeValidator> CompareValidator Control The CompareValidator control compares a value in one control with a fixed value or a value in another control. It has the following specific properties: Properties Description Type It specifies the data type. ControlToCompare It specifies the value of the input control to compare with. ValueToCompare It specifies the constant value to compare with. Operator It specifies the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck. The basic syntax of the control is as follows: <asp:CompareValidator ID=”CompareValidator1″ runat=”server” ErrorMessage=”CompareValidator”> </asp:CompareValidator> RegularExpressionValidator The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular expression. The regular expression is set in the ValidationExpression property. The following table summarizes the commonly used syntax constructs for regular expressions: Character Escapes Description b Matches a backspace. t Matches a tab. r Matches a carriage return. v Matches a vertical tab. f Matches a form feed. n Matches a new line. Escape character. Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters. Metacharacters Description . Matches any character except n. [abcd] Matches any character in the set. [^abcd] Excludes any character in the set. [2-7a-mA-M] Matches any character specified in the range. w Matches any alphanumeric character and underscore. W Matches any non-word character. s Matches whitespace characters like, space, tab, new line etc. S Matches any non-whitespace character. d Matches any decimal character. D Matches any non-decimal character. Quantifiers could be added to specify number of times a character could appear. Quantifier Description * Zero or more matches. + One or more matches. ? Zero or one matches. {N} N matches. {N,} N or more matches. {N,M} Between N and M matches. The syntax of the control is as given: <asp:RegularExpressionValidator ID=”string” runat=”server” ErrorMessage=”string” ValidationExpression=”string” ValidationGroup=”string”> </asp:RegularExpressionValidator> CustomValidator The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation. The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser can understand. The server side validation routine must be called from the control”s ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net. The basic syntax for the control is as given: <asp:CustomValidator ID=”CustomValidator1″ runat=”server” ClientValidationFunction=.cvf_func. ErrorMessage=”CustomValidator”> </asp:CustomValidator> ValidationSummary The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation. The following two mutually inclusive properties list out the error message: ShowSummary : shows the error messages in specified format. ShowMessageBox : shows the error messages in a separate window. The syntax for the control is as given: <asp:ValidationSummary ID=”ValidationSummary1″ runat=”server” DisplayMode = “BulletList” ShowSummary = “true” HeaderText=”Errors:” /> Validation Groups Complex pages have different groups of information provided in different panels. In such situation, a need might arise for performing validation separately for separate group. This kind of situation is handled using validation groups. To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property. Example The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. Here, we use the validation controls to validate the user input. This is the form in design view: The content file code is as given: <form id=”form1″ runat=”server”> <table style=”width: 66%;”> <tr> <td class=”style1″ colspan=”3″ align=”center”> <asp:Label ID=”lblmsg” Text=”President Election Form : Choose your president” runat=”server” /> </td> </tr> <tr> <td class=”style3″> Candidate: </td> <td class=”style2″> <asp:DropDownList ID=”ddlcandidate” runat=”server” style=”width:239px”> <asp:ListItem>Please Choose a Candidate</asp:ListItem> <asp:ListItem>M H Kabir</asp:ListItem> <asp:ListItem>Steve Taylor</asp:ListItem> <asp:ListItem>John Abraham</asp:ListItem> <asp:ListItem>Venus Williams</asp:ListItem> </asp:DropDownList> </td> <td> <asp:RequiredFieldValidator ID=”rfvcandidate” runat=”server” ControlToValidate =”ddlcandidate” ErrorMessage=”Please choose a candidate” InitialValue=”Please choose a candidate”> </asp:RequiredFieldValidator> </td> </tr> <tr> <td class=”style3″> House: </td> <td class=”style2″> <asp:RadioButtonList ID=”rblhouse” runat=”server” RepeatLayout=”Flow”> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Yellow</asp:ListItem> <asp:ListItem>Green</asp:ListItem> </asp:RadioButtonList> </td> <td> <asp:RequiredFieldValidator ID=”rfvhouse” runat=”server” ControlToValidate=”rblhouse” ErrorMessage=”Enter
ASP.NET – Custom Controls
ASP.NET – Custom Controls ”; Previous Next ASP.NET allows the users to create controls. These user defined controls are categorized into: User controls Custom controls User Controls User controls behaves like miniature ASP.NET pages or web forms, which could be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following characteristics: They have an .ascx extension. They may not contain any <html>, <body>, or <form> tags. They have a Control directive instead of a Page directive. To understand the concept, let us create a simple user control, which will work as footer for the web pages. To create and use the user control, take the following steps: Create a new web application. Right click on the project folder on the Solution Explorer and choose Add New Item. Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the footer.ascx contains only a Control directive. <%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”footer.ascx.cs” Inherits=”customcontroldemo.footer” %> Add the following code to the file: <table> <tr> <td align=”center”> Copyright ©2010 TutorialPoints Ltd.</td> </tr> <tr> <td align=”center”> Location: Hyderabad, A.P </td> </tr> </table> To add the user control to your web page, you must add the Register directive and an instance of the user control to the page. The following code shows the content file: <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”customcontroldemo._Default” %> <%@ Register Src=”~/footer.ascx” TagName=”footer” TagPrefix=”Tfooter” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title> Untitled Page </title> </head> <body> <form id=”form1″ runat=”server”> <div> <asp:Label ID=”Label1″ runat=”server” Text=”Welcome to ASP.Net Tutorials “></asp:Label> <br /> <br /> <asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Copyright Info” /> </div> <Tfooter:footer ID=”footer1″ runat=”server” /> </form> </body> </html> When executed, the page shows the footer and this control could be used in all the pages of your website. Observe the following: (1) The Register directive specifies a tag name as well as tag prefix for the control. <%@ Register Src=”~/footer.ascx” TagName=”footer” TagPrefix=”Tfooter” %> (2) The following tag name and prefix should be used while adding the user control on the page: <Tfooter:footer ID=”footer1″ runat=”server” /> Custom Controls Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link Library (DLL) and used as any other ASP.NET server control. They could be created in either of the following way: By deriving a custom control from an existing control By composing a new custom control combing two or more existing controls. By deriving from the base control class. To understand the concept, let us create a custom control, which will simply render a text message on the browser. To create this control, take the following steps: Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer. In the New Project dialog box, select ASP.NET Server Control from the project templates. The above step adds a new project and creates a complete custom control to the solution, called ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be added as a reference to the web site before registering it on a page. To add a reference to the existing project, right click on the project (not the solution), and click Add Reference. Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution Explorer should show the reference. To use the control on a page, add the Register directive just below the @Page directive: <%@ Register Assembly=”CustomControls” Namespace=”CustomControls” TagPrefix=”ccs” %> Further, you can use the control, similar to any other controls. <form id=”form1″ runat=”server”> <div> <ccs:ServerControl1 runat=”server” Text = “I am a Custom Server Control” /> </div> </form> When executed, the Text property of the control is rendered on the browser as shown: Working with Custom Controls In the previous example, the value for the Text property of the custom control was set. ASP.NET added this property by default, when the control was created. The following code behind file of the control reveals this. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomControls { [DefaultProperty(“Text”)] [ToolboxData(“<{0}:ServerControl1 runat=server></{0}:ServerControl1 >”)] public class ServerControl1 : WebControl { [Bindable(true)] [Category(“Appearance”)] [DefaultValue(“”)] [Localizable(true)] public string Text { get { String s = (String)ViewState[“Text”]; return ((s == null) ? “[” + this.ID + “]” : s); } set { ViewState[“Text”] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } } } The above code is automatically generated for a custom control. Events and methods could be added to the custom control class. Example Let us expand the previous custom control named SeverControl1. Let us give it a method named checkpalindrome, which gives it a power to check for palindromes. Palindromes are words/literals that spell the same when reversed. For example, Malayalam, madam, saras, etc. Extend the code for the custom control, which should look as: using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomControls { [DefaultProperty(“Text”)] [ToolboxData(“<{0}:ServerControl1 runat=server></{0}:ServerControl1 >”)] public class ServerControl1 : WebControl { [Bindable(true)] [Category(“Appearance”)] [DefaultValue(“”)] [Localizable(true)] public string Text { get { String s = (String)ViewState[“Text”]; return ((s == null) ? “[” + this.ID + “]” : s); } set { ViewState[“Text”] = value; } } protected override void RenderContents(HtmlTextWriter output) { if (this.checkpanlindrome()) { output.Write(“This is a palindrome: <br />”); output.Write(“<FONT size=5 color=Blue>”); output.Write(“<B>”); output.Write(Text); output.Write(“</B>”); output.Write(“</FONT>”); } else { output.Write(“This is not a palindrome: <br />”); output.Write(“<FONT size=5 color=red>”); output.Write(“<B>”); output.Write(Text); output.Write(“</B>”); output.Write(“</FONT>”); } } protected bool checkpanlindrome() { if (this.Text != null) { String str = this.Text; String strtoupper = Text.ToUpper(); char[] rev = strtoupper.ToCharArray(); Array.Reverse(rev); String strrev = new String(rev); if (strtoupper == strrev) { return true; } else { return false; } } else { return false; } } } } When you change the code for the control, you must build the solution by clicking Build –> Build Solution, so that the changes
ASP.NET – Life Cycle
ASP.NET – Life Cycle ”; Previous Next ASP.NET life cycle specifies, how: ASP.NET processes pages to produce dynamic output The application and its pages are instantiated and processed ASP.NET compiles the pages dynamically The ASP.NET life cycle could be divided into two groups: Application Life Cycle Page Life Cycle ASP.NET Application Life Cycle The application life cycle has the following stages: User makes a request for accessing application resource, a page. Browser sends this request to the web server. A unified pipeline receives the first request and the following events take place: An object of the class ApplicationManager is created. An object of the class HostingEnvironment is created to provide information regarding the resources. Top level items in the application are compiled. Response objects are created. The application objects such as HttpContext, HttpRequest and HttpResponse are created and initialized. An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request. ASP.NET Page Life Cycle When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then it is unloaded from the memory. At each of these steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code. The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives, are part of this control tree. You can see the control tree by adding trace= “true” to the page directive. We will cover page directives and tracing under ”directives” and ”event handling”. The page life cycle phases are: Initialization Instantiation of the controls on the page Restoration and maintenance of the state Execution of the event handler codes Page rendering Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code. Following are the different stages of an ASP.NET page: Page request – When ASP.NET gets a page request, it decides whether to parse and compile the page, or there would be a cached version of the page; accordingly the response is sent. Starting of page life cycle – At this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set. Page initialization – At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and the themes are applied. For a new request, postback data is loaded and the control properties are restored to the view-state values. Page load – At this stage, control properties are set using the view state and control state values. Validation – Validate method of the validation control is called and on its successful execution, the IsValid property of the page is set to true. Postback event handling – If the request is a postback (old request), the related event handler is invoked. Page rendering – At this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Response property of page. Unload – The rendered page is sent to the client and page properties, such as Response and Request, are unloaded and all cleanup done. ASP.NET Page Life Cycle Events At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle. Following are the page life cycle events: PreInit – PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler. Init – Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler. InitComplete – InitComplete event allows tracking of view state. All the controls turn on view-state tracking. LoadViewState – LoadViewState event allows loading view state information into the controls. LoadPostData – During this phase, the contents of all the input fields are defined with the <form> tag are processed. PreLoad – PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler. Load – The Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler. LoadComplete – The loading process is completed, control event handlers are run, and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler PreRender – The PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered. PreRenderComplete – As the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase. SaveStateComplete – State of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler. UnLoad