ASP.NET supports three different development models. They are
1. Web Pages,
2. MVC (Model View Controller)
3. Web Forms
Single Pages Model
Simplest ASP.NET model.
Similar to PHP and classic ASP.
Built-in templates and helpers for database, video, graphics, social media and more.
MVC(Model View Controller):
MVC separates web applications into 3 different components:
Models for data
Views for display
Controllers for input
Event Driven Model
The traditional ASP.NET event driven development model:
Web pages with added server controls, server events, and server code.
Features of ASP.Net:
1. ASP.NET is a new ASP generation. It is not compatible with Classic ASP, but ASP.NET may include Classic ASP.
2. ASP.NET pages are compiled, which makes them faster than Classic ASP.
3. ASP.NET has better language support, a large set of user controls, XML-based components, and integrated user authentication.
4. ASP.NET pages have the extension .aspx, and are normally written in VB (Visual Basic) or C# (C sharp).
5. User controls in ASP.NET can be written in different languages, including C++ and Java.
6. When a browser requests an ASP.NET file, the ASP.NET engine reads the file, compiles and executes the scripts in the file, and returns the result to the browser as plain HTML.
Benefits of Asp.Net
1. Asp.Net makes development simple and easy to maintain with event-driven and server side programming model.
2. Asp.Net source code is executed on the server. The source code is complied first time the page is requested. The server serves the complied version of the page for use next time the page is requested.
3. Asp.Net provides validations controls.
4. The html produced by Asp.Net is sent back to the browser. The application code that we write is not sent back to the browser and is not stolen easily.
5. In Asp.Net business logic(in .cs class file) and presentation logic(in .aspx file) are in separate files.
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 like Onclick or handle. Asp.Net 3.5 & 4.0 page life cycle has following events in sequence :
It is is entry point of page life cycle. It checks IsPostBack property to check or recreate dynamic controls. In this we can set master pages dynamically & set and get profile property values.
It is is raised after all controls of page are initilised and skin properties are set. It is used to read or initialise control properties.
This indicates that page is completely initialised.
This event is called before loading the page in the RAM(memory). If any processing on a control or on page is required we use it.
This invokes the onload event of the page. In this we create connection to the database, get/set controls values and get/set view state values.
This indicates that page is completely loaded into memory.
we use this event to make final changes to the controls or page before rendering it to the browser.
View state of each control is saved before this event occurs. If we want to change the view state of any control then we use this event. This event can not be used to change the other properties of the controls.
This indicates that page is completely rendered to the browser.Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.
The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.We can use this event for closing files & database connection. This event occurs for each control.
ASP.NET Web Server Controls
Controls are small building blocks of the graphical user interface, which includes text boxes, buttons, check boxes, list boxes, labels and numerous other tools, using which users can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating master pages, data manipulation.
ASP.Net uses fourtypes of web controls, which are:
1.HTML server controls
HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render.
2. Web server controls
Controls with more built-in features than HTML server controls. Web server controls include not only form controls such as buttons and text boxes, but also special-purpose controls such as a calendar, menus, and a tree view control. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax.
Controls that incorporate logic to enable you to what users enter for input controls such as the TextBox control. Validation controls enable you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on. For more information, see ASP.NET Validation Controls.
Controls that you create as ASP.NET Web pages. You can embed ASP.NET user controls in other ASP.NET Web pages, which is an easy way to create toolbars and other reusable elements. For more information, see ASP.NET User Controls
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
Displays a sequence of images
Displays a push button
Displays a calendar
A day in a calendar control
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
Creates an item in a 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
Creates a list in bullet format
Displays a repeated list of items bound to the control
Sets the style of controls
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
Validation Controls in ASP.Net
We can easily validate the user input by using ASP.NET validation controls. It provides an easy to use mechanism for all common types of standard validation. This validation controls can be used with HTML and Web Server controls. Six validation controls are available with ASP.NET as of now, they are as follows.
The RequiredFieldValidator Control - Ensures that the user does not skip a mandatory entry field .
The CompareValidator Control – Compares one controls value with another controls value, constants and data type using a comparison operator (equals, greater than, less than, and so on).
The RangeValidator Control - Checks the user's input is in a given range (eg: numbers or characters).
The RegularExpressionValidator Control - Checks that the user's entry matches a pattern defined by a regular expression.
The CustomValidator Control - Checks the user's entry using custom-coded validation logic.
The ValidationSummary Control - Displays a summary of all validation errors inline on a web page, in a message box, or both.
All validation controls except ValidationSummary are used to validate the user input, whereas the ValidationSummary control is just used to display the entire validation error messages in a particular area. This error list can be printed in the browser and or displayed as a dialogue box. The CustomValidator allows you to implement your own validations. By using CustomValidator you can perform complex validations or you can validate the data from the database etc.
Validation Controls Common Properties and Methods
Apart from standard Font and other Formatting properties, the controls derived from BaseValidator class have the following properties in common.
ControlToValidate – ID of the control which we are going to validate. The control must be developed using ValidatioPropertyAttribute. So if you develop any user control that may require validation then add this attribute to your control class. Read More on ValidatioPropertyAttribute from MSDN.
Display – Display behavior of the error message in validation control, possible values are “None”, “Static”, ”Dynamic”. This property is explained in coming section.
None - The validation message is never displayed.
Static - The control displays an error message if validation fails. Space for the validation message is allocated in the layout of the page even if the input passes validation.
Dynamic - The control displays an error message if validation fails. Space for the validation message is dynamically added to the page if validation fails. (If client-side validation is not active Static and Dynamic behave the same way).
EnableClientScript – Use this property to enable or disable client-side validation.
Enabled – Use this property to enable or disable the validation control. If this property is set to false then it will prevent validation being performed.
ErrorMessage – Error message displayed in a ValidationSummary control when validation fails.
Text – Error Message displayed in the validation control when validation fails. I have given another section on Difference between Text and ErrorMessage property.
SetFocusOnError – Boolean value used to set focus to the control mentioned in the ControlToValidate when validation fails.
ValidationGroup – The name of the validation group to which this validation control belongs, Detailed explanation is given in another section.
IsValid – Boolean value that indicates the validation status.
ASP.NET - State Management:
HTTP ( Hyper Text Transfer Protocol) is a stateless protocol. When the client disconnects from the server, the ASP.Net engine discards the page objects. This way each web application can scale up to serve numerous requests simultaneously without running out of server memory.
However, there need to be some technique to store the information between requests and to retrieve it when required. This information i.e., the current value of all the controls and variables for the current user in the current session is called the State.
ASP.Net manages four types of state:
1. View State
2. Control State
3. Session State
4. Application State
The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is again post back the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
The entire application - by setting the EnableViewState property in the <pages> section of web.config file
A page - by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#" EnableViewState="false" %>
A control - by setting the Control.EnableViewState property.
Control state cannot be modified, accessed directly or disabled.
When a user connects to an ASP.Net website, a new session object is created. When session state is turned on, a new session state object is created for each new request. This session state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data like inventory or supplier list, or a customer record or shopping cart. It can also keep information about the user and his preference and keep track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of session state items.
An ASP.Net application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users.
To provide for the use of application state, ASP.Net creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc and to keep track of users visiting the site.
ASP.NET is an event-driven way of making web applications. With PHP and Classic ASP, you have one file, which is executed line after line, from start to end. However, ASP.NET is very different. Here we have events, which are either activated by the user in one way or another. In the previous example, we used the Page_Load method. Actually, this is an event, which the Page class calls when the page is loaded. We will use the same technique in the next example, where we will add a couple of controls to our simple hello world example. To make it a bit more interesting, we will change the "world" word with something defined by the user. Have a look at this codelisting, where we add two new controls: A Button control and a TextBox control.
<form id="form1" runat="server">
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
<br /><br />
<asp:TextBox runat="server" id="TextInput" />
<asp:Button runat="server" id="GreetButton" text="Say Hello!" />
As you can see, we now have the 2 new controls added, but they really can't do much at the moment. You can run the example if you wish to check this out for your self - if you click the button, the page is simply reloaded. Let's change that, and let's start by doing it the easy way. VS comes with a WYSIWYG editor, and while I hardly ever use it my self, it does make some things easier, like creating events.
So, click the Design button in the bottom of VS. Now you will see a visual representation of our page. We wish to add a Click event to the button, and this is very simply - just doubleclick the GreetButton, and you will be taken to the CodeBehind file of our page. As you can see, a fine new method has been added, called GreetButton_Click. If you have a look at the Default.aspx file (you need to go from Design view to Source view), you will see that an attribute has been added to our Button control, telling which method to call when the button is clicked. All this work done with a simple doubleclick.
Now lets add some code to our new event. We wish to use the text from the TextBox, on our good old Label with the "Hello, world!" text. This is also very simple, and all it requires is a single line of code:
HelloWorldLabel.Text = "Hello, " + TextInput.Text;
Run the project again (F6), and you will see the our old page with a couple of new controls. The "Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a name in the textbox, and press the button. Voila, the text is changed, and we have just used our first control event. Notice how we can add code which is not necessarily called unless the user performs a specific task. This is different from the good old Classic ASP/PHP approach, but you will soon get used to it, and you will probably also come to like it a lot!