You are on page 1of 29

Working with Web Application

Overview

ASP.NET Application -An Overview Saving Data of Web Forms Event Handling in a Web Application Using Custom Controls

State Management
We are working in a connectionless environment Which means we cant use normal variables to persist data between server round trips, and pages. Instead we have a range of techniques provided by Asp.Net and HTTP that we can use:

State Management

Between Server Round Trips


In A Session
Session Variables Cookies Cookies (with expiry) Database or other storage Application Variable Cache Object appSettings in Web.Config

ViewState Hidden form fields Querystrings HTML Forms Querystrings Server.Transfer Cookies
HTML Forms

Between Sessions

Between Pages

Application

ViewState
ASP.Net mechanism to persist data through server round trips on a single page. All ASP controls (including the Page object) have EnableViewState property that is defaulted to true You can add your own data to view state using : [c#] ViewState.Add("MyVariable,MyValue); vb] ViewState.Add(MyVariable,MyValue) ViewState materializes as a hidden field in the HTML output, with all the ViewState values encoded to ensure they come from the page that created them.

HTML Forms
Since ASP.NET requires a HTML Form that posts back to itself, and you can't nest forms in HTML this technique is limited. However you could add a normal HTML form below the ASP.NET form and post to a different page from that. Or you can add normal HTML form elements (such as a TextField) inside the ASP.NET form Then you can retreive these values using the Request.Form collection: [c#] MyValue = Request.Form["MyVariable"]; [vb] MyValue = Request.Form("MyVariable)

Querystrings
Querystring can pass data from one page to another, even across web sites and servers. Can by simple a URL in a hyperlink:
<A href="anotherpage.aspx?MyVariable=MyValue&MyOtherV ariable=MyOtherValue">Click me</a>

QueryStrings

Or you could use a redirect in code: [c#]


Response.Redirect(" anotherpage.aspx?MyVariable=MyValue&MyOtherVariabl e=MyOtherValue"); [vb] Response.Redirect(" anotherpage.aspx?MyVariable=MyValue&MyOtherVariabl e=MyOtherValue");

QueryStrings
Read querystring values through Request.QueryString [c#] MyValue = Request.QueryString["MyVariable"]; [vb] MyValue = Request.QueryString("MyVariable)

Server.Transfer and Context.Items

Use to pass a variable from one to another without changing the Page URL. In the first page, and the values you want to the Content.Items collection:
[c#] Context.Items.Add("MyVariable,MyValue);

Then transfer to the second page: [c#] Server.Transfer("SecondPage.aspx");

Server.Transfer and Context.Items

On the second page retrieve the value from the Context.Items collection and cast to the type you need:
[c#] MyValue = (MyType)Context.Items["MyVariable"]; [vb] MyValue = Ctype(Context.Items("MyVariable),MyType)

Cookies
Cookies store data in the browser
Either memory resident only (because no Expiry Date is given) and so only available throughout a session. Or if an Expiry Date is given then Cookies will persist between sessions for a user (with a consistent profile, login or machine)
[c#] HttpCookie ck = new HttpCookie("MyVariable",MyValue); [vb] Dim ck as new HttpCookie("MyVariable",MyValue)

Cookies
Create a cookie using HttpCookie and then add it to Response.Cookies collection to send it to the browser.
[c#] ck.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(ck); [vb] ck.Expires = DateTime.Now.AddDays(30) Response.Cookies.Add(ck)

Cookies
Read a cookie by retrieving it from the Request.Cookies collection: [c#] HttpCookie ck; ck = Request.Cookies["MyVariable"]; [vb] Dim ck as HttpCookie ck = Request.Cookies("MyVariable)

Cookies
Delete a cookie by setting it's expiry date to yesterday (or earlier) and adding to the Response.Cookies collection

[c#] ck.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(ck);


[vb] ck.Expires = DateTime.Now.AddDays(-1) Response.Cookies.Add(ck)

Session State

Session state is maintained on a per-client basis. When a client first accesses any page in an application, an ASP.NET generated session ID is created. Session state is used for things like:
Shopping carts, Viewing preferences, other

Session state is the most flexible and, in general, the most efficient means of maintaining client-specific state.

Session Events

Event Session_OnStart

Description Occurs when a new user accesses a page thats part of the application. Can be used to initialize: session variables, session level objects, and begin database connections.

Session_OnEnd

Happens when a session times out. Can be used to any final cleanup and to close a database connection.

Using the Session Object


Session state is maintained on behalf of each client within an ASP.NET application. When a new client begins to interact with the application, a new session ID (or session key) is generated The ID is associated with all subsequent requests from that same client. The state is retained in memory on the server in the default session state configuration. By default, the session key is retained on the client side in a cookie. (there is an alternative in cases where cookies do not work)

Application State
Application state is where information that is global to the application may be stored. For efficiency, this state is typically stored once and then read from many times. Often used for application statistics variables or constant global data:
Number of users who have accessed site Counts of different types of browsers Can prefetch static data from a database or file

Should be used with care

Application Events
Event Application_OnStart Description Happens once when the first user access the app. Can be used to retrieve or initialize information that will be used across all sessions.

Application_OnEnd

Happens once when the last user leaves the app. Can be used to clean up any app-level variables and objects.

Application_OnBeginRequest

Happens every time a page in the application is requested, before the request is serviced.

Application_OnEndRequest

Happens after each request is serviced. The last event that can have

an effect on the response.

Using the Application Object


Application object is implicitly locked for you when data is read from or written to it. May make more sense to avoid using application object and use data cache if you are just storing global constants. Application object must be used if you are using shared, updatable data.

Event Handling

Event Handling in ASP.NET


Events are messages sent out by objects
Different objects Different messages

In ASP.NET events occur when the server detects an event


Page-Level events
Occur when users visits a web page

Control events
Occur when a user manipulates an ASP.NET control

Page Events

Web Form trigger 11 events when loaded (in order)


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. Initialization (Page_Init) Load View State Post Back Data Processing Page Load (Page_Load) Post Back Change Notification Post Back Event Processing Pre-rendering (Page_PreRender) Same view State Rendering Disposing Unload

Page Level Events

These events do not need to be registered Most common Used Page Event is Page_Load
<script runat="server"> protected void Page_Load(Object Src, EventArgs E) { if (!PostBack) DataBind(); } </script>

Example (code)

Control Events
Must have registered Handlers
Use Delegates which listen for events and then delegating responsibility for the event to the assigned handler Generally event handlers (like Page_Load) have two parameters
Object src
The object which created the event

EventArgs E
Specific information about the event

Creating a handler for a ASP.NET Control

ASP.NET Control must be in a Web Form that is set to runat=server

Control Events

The Dreamweaver wizard will register the event but you still need to write the handler code
Between <script> tags in Head
void btnTest_OnClick( Object Src, EventsArgs E) { Some C# code }

Adding Controls and Events Programmatically

Between <script> tags in head


Button btnTest = new Button(); btnTest.Text = daButton; btnTest.Click += new EventHandler(this.btnTest_OnClick); samePanel.Controls.Add(btnTest); Make sure you write the btnTest_Onclick functions

You might also like