Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Web Forms Andy Scrase.NET developer, Christchurch NZ

Similar presentations


Presentation on theme: "1 Web Forms Andy Scrase.NET developer, Christchurch NZ"— Presentation transcript:

1 1 Web Forms Andy Scrase.NET developer, Christchurch NZ andy@scrase.com

2 2 Objectives Introduce Web Forms –Control-based programming model Present server side controls –Html controls –Web controls Discuss tools for building web forms –Visual Studio.NET –WebMatrix

3 3 Control-based programming Control-based programming is a familiar paradigm –Desktop application development libraries have used control- based programming for years –A program consists of a collection of controls –Each control knows how to render its state to the screen –The developer manipulates the state of these controls and lets rendering happen implicitly

4 4 Conceptual model for control-based programming

5 5 Control-based programming for web applications ASP.NET brings control-based programming to web apps –Server-side objects created to represent elements of a page –Each server-side object capable of rendering itself as HTML –Layered on top of Request/Response architecture of HTTP –Some desktop paradigms work well –Others must be re-thought

6 6 Conceptual model for web forms applications

7 7 Server-side controls The web forms model is based on a set of primitive controls –Called server-side controls as they exist on the server and provide rendering to the client as HTML –Created using runat=server attribute on traditional HTML elements in a.aspx page –Can be referenced within server-side code using designated ID –Implicitly added as member variables to the generated Page- derived class definition

8 8 Enter name: Personality: extraverted introverted in-between Hi, you selected An ASP.NET page using server-side controls <%> <%> <%> <%>

9 9 using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; public class WebFormPage1_aspx : Page { protected HtmlInputText _name; protected ListItem __control3; protected ListItem __control4; protected ListItem __control5; protected HtmlSelect _personality; protected HtmlForm __control2; //... } Generated Page-derived class with server-side controls

10 10 Server-side control state management Server-side controls must manage their state –Initial GET request to a page creates the server side controls with their default values –Subsequent POST requests back to the same page creates the server side controls with the values in the POST body –Any changes made to the value of the controls during the processing of a request will be reflected when the page is rendered

11 11 ClientServer page1_aspx instance #1 _name.Value _personality.Value "" page1_aspx instance #2 _name.Value _personality.Value "Sam" "introverted" GET /test/page1.aspx HTTP/1.1 submit request HTTP/1.1 200 OK... renders response returned client interaction POST /test/page1.aspx HTTP/1.1... _name=Sam&_personality=introverted submit pressed submit request HTTP/1.1 200 OK... <input id="_name" type="text" value="Sam" />... renders response returned WebForm Client Interaction

12 12 Server Control Behaviors Server controls retain their state between POST requests back to the same page –No need to re-initialize state on POST-back requests –Can not be used for cross-page POST requests –Controls that are not intrinsically included in a POST request have their state propagated via a hidden field (ViewState) More on this later

13 13 HtmlControls HtmlControls are server-side representations of standard HTML elements –Any HTML element in an ASPX page marked with the runat=server attribute will become an HTML control on the server –All derive from HtmlControl class –HTML elements with no distinguished server-side functionality (like div, span, etc.) are all represented as HtmlGenericControl instances

14 14 Hierarchy of HtmlControls and the tags they map to

15 15 click me check me cell00 cell01 cell10 cell11 A sample ASP.NET page written with HtmlControls

16 16 WebControls WebControls provide a more consistent object model and a higher level of abstraction than HtmlControls –Most HTML elements can also be represented as WebControls on the server –WebControl versions typically have a more consistent interface (background color is always BackColor property whereas in HTML it may be a style attribute (span) or a property (table) ) –WebControls also provide higher-level controls with more functionality than primitive HTML elements (like the Calendar control) –WebControls may render themselves differently based on client browser capabilities

17 17 Hierarchy of WebControls

18 18 <asp:TextBox TextMode="MultiLine" rows="3" Text="type more in me" runat="server" /> cell00 cell01 cell10 cell11 A sample ASP.NET page written with WebControls

19 19 Page Lifecycle Each request to a page results in a new instance of that class –Page state is not retained between requests Several events defined by the Page class –Useful to define handlers in code-behind classes –4 events called in sequence during a page's lifetime –Possible to subscribe to these events in three ways Explicitly subscribing a delegate to the event Overriding virtual function handlers in base class Defining functions named Page_xxx with AutoEventWireup set to true

20 20 public class Page : TemplateControl, IHttpHandler { // Events public event EventHandler Init; public event EventHandler Load; public event EventHandler PreRender; public event EventHandler Unload; // Pre-defined event handlers protected virtual void OnInit(EventArgs e); protected virtual void OnLoad(EventArgs e); protected virtual void OnPreRender(EventArgs e); protected virtual void OnUnload(EventArgs e); } Events in the Page class

21 21 public class EventsPage : Page { // Override OnInit virtual function to manually // subscribe a delegate to the Load event protected override void OnInit(EventArgs e) { this.Load += new EventHandler(MyLoadHandler); base.OnInit(e); } // Load event handler protected void MyLoadHandler(object src, EventArgs e) { Response.Write(" rendered at top of page "); } } Example: Adding event handlers using virtual function overriding and manual delegate subscription

22 22 protected void Page_Load(object src, EventArgs e) { Response.Write(" Load event fired! "); } AutoEventWireup Page Example: Adding event handlers using AutoEventWireup defaults to true

23 23 Server-side control state initialization The Load event of the Page class is commonly where control state is initialized –Invoked after controls have been created, but before rendering –Because controls retain their state across POST requests, it is usually only necessary to initialize their state once // Common control interaction if (!IsPostBack) initialize control state else look at/process client-submitted state

24 24 Sample Page Initializing Control State In OnLoad protected override void OnLoad(EventArgs e) { if (!IsPostBack) { _lb.Items.Add(new ListItem("item 1")); _lb.Items.Add(new ListItem("item 2")); _lb.Items.Add(new ListItem("item 3")); _lb.Items.Add(new ListItem("item 4")); } else _message.Text = string.Format("You selected {0}", _lb.SelectedItem.Text); base.OnLoad(e); }

25 25 Events Many server-side controls can generate server-side events –Exposed as standard CLR EventHandler delegates –To subscribe to an event of a server-side control Construct a new instance of the EventHandler delegate Initialize it with your handler function pointer Subscribe the delegate to the control's event –Alternatively, you can subscribe to an event by Indicating your handler function with the OnEvent attribute in the control's tag

26 26 protected void OnClickMyButton(object src, EventArgs e) { _message.Text = "You clicked the button!"; } protected override void OnInit(EventArgs e) { _MyButton.Click += new EventHandler(OnClickMyButton); base.OnInit(e); } ASP.NET event page Server-side event handler using explicit delegate subscription

27 27 protected void OnClickMyButton(object src, EventArgs e) { _message.InnerText = "You clicked the button!"; } ASP.NET event page <input type="button" id="_MyButton" value="Click me!" OnServerClick="OnClickMyButton" runat="server" /> Server-side event handler using OnEvent syntax

28 28 Events in the Page Lifecycle Events are issued after the Load event, but prior to rendering Very common control interaction is: –In Load event handler, initialize control state (when IsPostBack is False) –In server-side event handlers for controls (OnButtonClick...), process client-submitted state

29 29 protected override void OnLoad(EventArgs e) { if (!IsPostBack) { _lb.Items.Add(new ListItem("item 1")); _lb.Items.Add(new ListItem("item 2")); _lb.Items.Add(new ListItem("item 3")); _lb.Items.Add(new ListItem("item 4")); } base.OnLoad(e); } protected void OnEnter(object src, EventArgs e) { _message.Text = string.Format("You selected {0}", _lb.SelectedItem.Text); } Server-side event with control state interaction

30 30 Page event sequencing It is critical to understand the event sequencing of the Page –Pages are created and discarded with each request –There is an explicit, deterministic sequences of events that occurs with the lifetime of each page –It is important to know where in that sequence you should perform tasks When can I look at a control's contents? When can I modify a control's contents? When is the Request object available?...

31 31 Page POST-back event sequence

32 32 Web Forms and Code-behind Server-side controls in combination with code-behind enables true separation of page logic from page layout and rendering –Server-side controls must be declared in code-behind class as public or protected variables with names matching control IDs –During parsing of the.aspx page, ASP.NET will look for member variables with matching names in the base class If it finds a variable of the appropriate type, it will use it Otherwise it will create a new member variable in the.aspx-generated class definition

33 33 <%@ Page Language="C#" Inherits="Page2" Src="Page2.cs" AutoEventWireUp="false" %> Enter name: Personality: Page with server-side controls using code-behind <%@ Page Language="C#" Inherits="Page2" Src="Page2.cs" AutoEventWireUp="false" %>

34 34 public class Page2 : Page { protected HtmlSelect _personality; protected HtmlInputText _name; protected HtmlInputButton _enterButton; protected HtmlGenericControl _messageParagraph; override protected void OnInit(EventArgs e) { _enterButton.ServerClick += new EventHandler(OnEnter); } override protected void OnLoad(EventArgs e) { if (!IsPostBack) { _personality.Items.Add(new ListItem("extraverted")); _personality.Items.Add(new ListItem("introverted")); _personality.Items.Add(new ListItem("in-between")); } } protected void OnEnter(object src, EventArgs e) { string msg = string.Format("Hi {0}, you selected {1}", _name.Value, _personality.Value); _messageParagraph.InnerText = msg; } } Code-behind file for server-side control page

35 35 Web Forms Applications with Visual Studio.NET Visual Studio.NET supports creating Web projects –Generates new virtual directory for your project –Project output is a single assembly containing all code-behind, deployed in the /bin directory –Designer support for WebForms with automatic code-behind updates –Wizards for standard web components (web forms, user controls, etc.) Standard ClassLibrary projects can be used to create ASP.NET applications as well

36 36 Web Form Generation Codebehind attribute used by VS.NET to associate code-behind file with.aspx file (not equivalent to src=)

37 37 Code-behind for VS.NET WebForm namespace WebFormsApp { public class WebForm1 : Page { protected Button _PushMe; protected TextBox _Name; private void Page_Load(object sender, EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { _PushMe.Click += new System.EventHandler(Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Button1_Click(object sender, EventArgs e) { } } OnInit override with call to InitializeComponent Explicit event wire-up Server-control member variables Load event handler

38 38 WebMatrix Free ASP.NET development tool from Microsoft –Hosts its own web server (can build and test without IIS) –Many shared features with VS.NET Page designer, wizards, syntax highlighting,... –What's missing Intellisense, Project creation, code-behind support,... Download from: http://www.asp.net/webmatrix

39 39 Summary ASP.NET brings control-based programming to web development Server-side controls retain state between post-backs HtmlControls provide server-side equivalents of HTML elements WebControls provide more consistent object model for server-side controls, as well as some more sophisticated controls


Download ppt "1 Web Forms Andy Scrase.NET developer, Christchurch NZ"

Similar presentations


Ads by Google