Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Forms and Server Controls ASP.NET. Using HTML Server Controls All HTML tags can be changed into server-side tags using the attribute and value runat="server"

Similar presentations


Presentation on theme: "Web Forms and Server Controls ASP.NET. Using HTML Server Controls All HTML tags can be changed into server-side tags using the attribute and value runat="server""— Presentation transcript:

1 Web Forms and Server Controls ASP.NET

2 Using HTML Server Controls All HTML tags can be changed into server-side tags using the attribute and value runat="server" – Limited functionality compared to Web controls – Provide output similar to their HTML counterparts To set the runat attribute: – Right-click on the HTML control and select the command Run As Server Control or – Type the attribute and value into the tag in HTML view, i.e.

3 HTML Server Controls Similar to HTML Controls but run on the server Divided into separate classes: – HTMLInputControl – HTMLContainerControl

4 HTML Server Controls

5 HTML Control Client-Side vs. Server- Side Event Handlers In HTML documents, client-side controls (i.e. scripts or procedures executing in JavaScript or VbScript) have events such as onClick and onChange – Associated with HTML client controls When an HTML Server control value has changed, the OnServerChange or OnServerClick event occurs

6 The Line Continuation Character Line continuation characters When writing code, never press key in the middle of a statement within code behind the page Underscore (_) key preceded by a blank space allows the statement to be continued on next line Example: lblMaturity.InnerHtml = sngInvestment _ * (1 + sngRate / 36000) _ ^ (360 * intYears) – (Single-line statement)

7 Concatenation Joining of two or more strings into a single string using either of the operators "&" or "+" Formats: String1 & String2 -or- String3 + String4 Examples: strString = "Welcome to " & "ASP.NET" – Stores "Welcome to Visual Basic" into strString lblArithmetic.InnerHtml = "11 + 7 = " _ & 11 + 7 – Stores "11 + 7 = 18" into lblArithmetic.InnerHtml

8 HTML Server Control Event Handlers Controls that support the OnServerChange event: – HTMLInputCheckBox – HTMLInputRadioButton – HTMLInputHidden – HTMLInputText – HTMLTextArea – HTMLSelect Controls that support the OnServerClick event: – HTMLInputImage – HTMLAnchor – HTMLButton – HTMLForm

9 Starting a New Web Form 1.Select Project from the menu bar 2.Select Add Web Form… from the Project menu – The "Web Form" icon will already be selected in the Templates: frame of the "New Item" dialog window 3.Type the Name: for the new file – The extension ".aspx" will be added automatically when the file is created 4.Click the button

10 HTMLButton.aspx

11 Properties of the individual controls can be changed through "Properties" window The Style property (attribute) is modified using Style Builder dialog window (same as for style sheets) Additionally many properties can be changed by adding statements to the code behind the page – When page loads, or when an event occurs, such as a button click Properties frequently are not the same for HTML server controls and ASP.NET server controls Properties

12 "Font" Properties in Style Builder

13 "Position" Properties in Style Builder

14 HTMLButton.aspx (Page 1) Add the image header.jpg – Style property—Position tab Top=0; Left=0 Add the image menu.gif – Style property—Position tab Top = 85; Left = 17 Add the image waterfordgifts.jpg – Style property—Position tab Top = 38; Left = 134

15 The ID and Name Properties The ID property is used to identify the control to the server for server-side processing The Name property identifies the control to scripts running on the client side

16 HTMLButton.aspx (Page 2) Add a Label from the "HTML" tab in the Toolbox – Set attribute "runat = server" (right-click and select command Run as Server Control) – ID—lblTitle – Name—(we will not be setting this property) – Style Font (Family=Trebuchet MS; Size=15) Position (Top=243; Left=139; Height=26; Width=365) – Modify text by typing—"Select the gender of the gift recipient"

17 HTMLButton.aspx (Page 3) Add a Button from the "HTML" tab in the Toolbox – Set attribute "runat=server" – ID—btnMale – Style (Top=278; Left=138; Height=27; Width=89) – Value—"Male" Add a Button from the "HTML" tab in the Toolbox – Set attribute "runat=server" – ID—btnFemale – Style (Top=310; Left=138; Height=27; Width=89) – Value—"Female"

18 HTMLButton.aspx (Page 4) Add a Label from the "HTML" tab in the Toolbox – Set attribute "runat = server" – ID—lblGiftIdeasWomen – Style Font (Family=Trebuchet MS; Size=12) Position (Top=275; Left=235; Height=210; Width=250)

19 HTMLButton.aspx (Page 5) Label—lblGiftIdeasWomen – Create a bulleted list— Make-Up Brush Tyrone Bell Butterfly Balmoral Vase Abbey Clock Heart-Shaped Ring Holder Wellsley Picture

20 HTMLButton.aspx (Page 6) Add a Label from the "HTML" tab in the Toolbox – Set attribute "runat = server" – ID—lblGiftIdeasMen – Style Font (Family=Trebuchet MS; Size=12) Position (Top=275; Left=235; Height=210; Width=250) (Wait to set the Left position until all text is entered)

21 HTMLButton.aspx (Page 6) Label—lblGiftIdeasMen – Create a bulleted list— Golf Ball Golf Club Male Golfer Letter Opener Business Card Holder Shamrock Paperweight

22 Procedures A procedure (Sub or Function)is a named grouping of one or more programming statements Create an event Sub procedure by double-clicking on the object in Design mode The Page_Load event occurs when the web page loads into the browser Example: Private Sub Page_Load( … ) Handles MyBase.Load lblGiftIdeasMen.Visible = False lblGiftIdeasWomen.Visible = False End Sub

23 The ServerClick Event Occurs when an HTML Server Button (HTML Button with runat=server attibute set) is clicked Equivalent of Click event in VB.NET, but for an ASP.NET Web Server control Example: Private Sub btnMale_ServerClick( … ) Handles btnMale.ServerClick … End Sub

24 The InnerHtml Property Modifies the contents of an HTML Label (or other) control May include HTML tags for formatting of the text The Label is converted to a tag with inserted text in the rendering of an HTML document Example: lblTitle.InnerHtml = " We have lots of gift ideas for men. " The InnerText property (similar to InnerHtml) may only contain text elements, not formatting tags

25 HTMLButton.aspx—Page_Load Private Sub Page_Load( … ) Handles MyBase.Load lblGiftIdeasMen.Visible = False lblGiftIdeasWomen.Visible = False End Sub

26 HTMLButton.aspx— btnMale_ServerClick Private Sub btnMale_ServerClick( … ) Handles btnMale.ServerClick lblTitle.InnerHtml = " We have lots of gift ideas for men. " lblGiftIdeasMen.Visible = True lblGiftIdeasWomen.Visible = False End Sub

27 HTMLButton.aspx— btnFemale_ServerClick Private Sub btnFemale_ServerClick( … ) Handles btnFemale.ServerClick lblTitle.InnerHtml = " We have lots of gift ideas for women. " lblGiftIdeasWomen.Visible = True lblGiftIdeasMen.Visible = False End Sub

28 An image is displayed on the Button instead of text – By default the image docks to the all sides on the button, so it stretches if the button is resized There actually is no Image Button in the HTML tab of the Toolbox – Drop and drag an HTML Button from the Toolbox – Then key the type attribute in the input tag, i.e. HTML Image Button (Page 1)

29 The src attribute names the path and filename of the image file displayed on the Button, i.e. No value attribute is required since image replaces the text on the button All other functioning is the same as the HTML Button control HTML Image Button (Page 2)

30 HTMLImageButton.aspx

31 btnMale btnFemale

32 The Value Property for a Text Field Retrieves or modifies the values from HTML text field (text box) controls – The value attribute can be used to set the default value for input controls such as a one-line text field or password box Used for HTML form controls rather than the Text property of ASP.NET server controls Examples: – txtUserName.Value – txtPassword.Value

33 HTML Button Controls Buttons usually call procedures when clicked Available are Submit, Reset, and the general Button Member of the HTMLInputControl Class, i.e. – Resets Form to default so runat="server" not applicable – Default procedure for HTML Buttons is ServerClick event, i.e Private Sub btnSubmit_ServerClick( … ) Handles btnSubmit.ServerClick

34 HTMLInputButton.aspx

35 HTMLInputButton.aspx (Page 1) Add Text Field from "HTML" tab in Toolbox – Set attribute "runat = server" – ID—txtUsername – Style (Top=280; Left=145) Add Password Field from "HTML" tab in Toolbox – Set attribute "runat = server" – ID—txtPassword – Style (Top=310; Left=145)

36 HTMLInputButton.aspx (Page 2) Add Submit Button from "HTML" tab in Toolbox – Set attribute "runat = server" – ID—btnSubmit – Style (Top=345; Left=150) – Value—"Sign In" Add Reset Button from "HTML" tab in Toolbox – ID—btnReset – Style (Top=345; Left=230)

37 HTMLInputButton.aspx (Page 3) Add a Button from "HTML" tab in Toolbox – Set attribute "runat = server" – ID—btnHelp – Style (Top=345; Left=450) – Value—"Help"

38 HTMLInputButton.aspx—Page_Load Private Sub Page_Load( … ) Handles MyBase.Load lblTitle.InnerText = "Please log into our Customer Support Area" lblHelp.Visible = False btnHelp.Visible = True End Sub

39 HTMLInputButton.aspx—Page_Load (Page 1) Private Sub btnSubmit_ServerClick( … ) Handles btnSubmit.ServerClick lblHelp.Visible = False If txtUsername.Text = "Course" And txtPassword.Text = "Technology" Then lblTitle.InnerText = "You are authenticated"

40 HTMLInputButton.aspx—Page_Load (Page 2) Else lblTitle.InnerText = "Please click on the Help button for help!" txtUsername.Text = "" txtPassword.Text = "" btnHelp.Visible = True End If End Sub

41 HTMLInputButton.aspx— btnHelp_ServerClick Private Sub btnHelp_Server_Click( … ) Handles btnHelp.ServerClick lblTitle.InnerText = "Please log into our Customer Support Area" lblHelp.Visible = True btnHelp.Visible = False End Sub

42 HTML Radio Button, Dropdown List, and Hyperlink Server Controls CheckBoxes, RadioButtons and DropDown lists – Form fields that allow users to select from lists of options – Can retrieve their values using properties of the HTML form control Hyperlinks – Allow you to create links to other pages or to internal targets within the same page

43 The Checked Property of RadioButtons Determines which RadioButton is Checked: If rdBridal.Checked = True Then lblTitle.InnerHtml = "Celebrate your Wedding!" imgTop.Src = "images/28.jpg" End If Or: If rdBridal.Checked Then lblTitle.InnerHtml = "Celebrate your Wedding!" imgTop.Src = "images/28.jpg" End If

44 The RadioButton HTML Server Control

45 Dropdown HTML Server Control Created with the HTML tag – tags create each individual item – A value attribute can be associated with each item in the list SelectedIndex property of the drop-down list box – A zero-based index indicating which item is selected – When nothing has been selected the SelectedIndex property returns the value -1 The Add method add items to the list dynamically in code when the page loads, or when an event occurs

46 The IsPostback Page Property Determines if the user has visited page before during the current session Important to know so that statements that initialize the page do not run again if page is revisited The _doPostBack function is generated automatically by ASP.NET – Passes to the Web server information concerning the object that called an event and parameters passed to it – The Boolean IsPostBack property recognizes if the page was visited previously from this information

47 The IsPostback Page Property and the Add Method of the Select Control Example: If Not Me.IsPostBack Then lblTitle.InnerHtml() = _ "Select gender of gift recipient." imgProduct.Visible = False ProductList.Visible = False CatList.Items.Add("Gifts for Men") CatList.Items.Add("Gifts for Women") End If

48 Dropdown HTML Server Control

49 Anchors (Hyperlinks) Creates a hyperlink to another Web document Example: Men The HRef property can change the URL for an tag in the code behind the page, i.e. AMale.HRef = "GiftsForMen.aspx" AFemale.HRef = "GiftsForWomen.aspx" AHome.HRef = "http://www.tarastore.com"

50 The Hyperlink Control

51 Using ASP.NET Web Form Controls Also known as Web Controls – Located on the Web Forms tab in the Toolbox – Inherit from the Web Control class ASP.NET controls can be logically grouped into: – Web Form controls – Rich controls – Data controls – Validation Controls – Mobile Controls

52 Syntax Differences for Assigning Text to a Label in Web Form Controls Text is assigned to a Label (and other controls) using the Text property, not InnerHtml or InnerText Example: Label1.Text = "Welcome to ASP.NET" – Web Form controls in ASP.NET follow a syntax that closely approximates that of Visual Basic.NET

53 Syntax Differences for Assigning Color Values in Web Form Controls Color is a class in.NET Framework derived from the System.Drawing.Color namespace – Assign the value using known colors referred to by name, i.e. MyControl.BorderColor = System.Drawing.Color.Green MyControl.BorderColor = Color.Green

54 The Color.FromName () Method Returns a color value from the Color class Values may be specific system-define color name or an RGB hexadecimal color value as a string Format: ControlName.ColorProperty = Color.FromName("SystemDefinedColor") Examples: MyControl.BackColor = Color.FromName("Red") MyControl.BackColor = Color.FromName("MenuText")

55 Syntax Differences for Assigning Image Properties in Web Form Controls Image control class produces an tag Properties of the Image control are different from HTML server controls as follows: – ImageURL—path to the image and filename; creates the src property – AlternateText—displays text when the image is not available; creates the alt property – ImageAlign—provides the image alignment; creates the align property

56 The Add Method for the DropDownList Web Form Control Adds options ( blocks) to the DropDownList Member of the Items collection of the Example: If Not IsPostBack Then dlCategory.Items.Add("Gifts") dlCategory.Items.Add("Jewelry") dlCategory.Items.Add("China and Crystal") dlCategory.Items.Add("Pottery") dlCategory.Items.Add("Clothing") dlCategory.Items.Add("Food") dlCategory.Items.Add("Books, Music, Video") dlCategory.Items.Add("Bridal") End If

57 The SelectedIndex Property of the DropDownList Web Form Control The SelectedIndex property is a zero-based index indicating which item in the DropDownList is selected When no item has been selected from DropDownList, the SelectedIndex property returns the value -1 Example: Select Case dlCategory.SelectedIndex Case 0 lblTitle.Text = _ "Let us help you find best gift!" imgTop.ImageUrl = "images/21.jpg" …

58 ASPSelect.aspx

59 In Design view, drag DropDownList control from "Web Forms" tab of Toolbox onto Form Set properties: – IDdlCategory – Height25 – Width155

60 ASPSelect.aspx—Page_Load Private Sub Page_Load( … ) Handles MyBase.Load If Not IsPostBack Then dlCategory.Items.Add("Gifts") dlCategory.Items.Add("Jewelry") dlCategory.Items.Add("China and Crystal") dlCategory.Items.Add("Pottery") dlCategory.Items.Add("Clothing") dlCategory.Items.Add("Food") dlCategory.Items.Add("Books, Music, Video") dlCategory.Items.Add("Bridal") End If End Sub

61 ASPSelect.aspx—Page_Click Enter the following code after the procedure header: Select Case dlCategory.SelectedIndex Case 0 lblTitle.Text = "Let us help you find the best gift!" imgTop.ImageUrl = "images/21.jpg"

62 Panel Web Form Controls The Panel control contains other controls and in the browser HTML creates a block Another method for setting properties, i.e.wrapping, absolute positioning, font type, and scrollbars A Label control inserted into the Panel, creates a tag in the rendered HTML code – Use the Text property to display the text Only allows for flow layout of elements – Use a Table or an HTML gridlayout

63 ASPPanel.aspx The Panel

64 Literal Web Form Controls Used to write content directly to the page, i.e. – Client-side HTML or text without an ID property The runat = "server" attribute may not be applied

65 Placeholder Web Form Control A container to store dynamically added server controls Does not produce any visible output without addition of other controls The inserted controls are instantiated using classes and constructors, and are added to the Controls collection of the Placeholder, i.e. Dim MyLink As New Hyperlink placeholder.Controls.Add(MyLink)

66 The "Target" Property of a Hyperlink Control Target—window or frame in which the Web page will load (open) – The reserved name windows are: _ blank—renders in a new window without frames (_new will also render in a new window) _parent—renders in the immediate frameset or window parent one level above _self—renders in frame with the current focus _top—renders in a full window without frames – Target also may be a named frame or window

67 ASPPlaceHolder.aspx

68 In Design view, the Placeholder control already is inserted onto Form Set properties: – IDplaceholder

69 ASPPlaceHolder.aspx—Page_Load After comment "Create a hyperlink", insert: Dim MyLink As New Hyperlink placeholder.Controls.Add(MyLink) With MyLink.Text = "Click here to see larger image".ForeColor = Color.FromName("#004040").Font.Name = "Trebuchet MS".Font.Size = MyLabel.Font.Size.Smaller.ID = "HLHome".NavigateURL = "images/LgButterfly.jpg".Target = "_blank" End With

70 CheckBox Web Form Control Unlike a RadioButton, more than one CheckBox can be Checked Code can look at the value of each CheckBox, i.e. Dim MyMessage As String MyMessage = " You selected: " If CB1.Checked Then MyMessage &= CB1.Text & " " End If

71 ASPCheckBox.aspx

72 In Design view, drag CheckBox control from "Web Forms" tab of Toolbox below last CheckBox on Form Set properties: – IDCB8 – Font—NameTrebuchet MS – Font—SizeX-Small – ForeColor#004040 – Style—PositionTop=??; Left=?? – TextSports in Ireland

73 ASPCheckBox.aspx—btnSubmit_Click Enter the following code after the procedure header: Dim MyMessage As String MyMessage = " You selected: " If CB1.Checked Then MyMessage &= CB1.Text & " " End If

74 Using Validation Controls (Page 1) Compare controls, or part of the controls such as the data, to a rule – Rule may require that the control contain any value, or require a specific form of data such as alphabetical or numeric. – The rule may specify what the data must be contained within a range of two values. – The rule may be very specific and require formatting such as uppercase letters and periods.

75 Using Validation Controls (Page 2) The five validation controls are: – RequiredFieldValidator—Makes sure a form field is not left blank – RangeValidator—Makes sure a field’s value falls between a given range – CompareValidator—Compares field with other values or values of other controls using relational operators – RegularExpressionValidator—Evaluates the data against a regular expression – CustomValidator—Evaluates data against custom criteria as defined in a programmer-define Function

76 Using Validation Controls (Page 3) Inherits from the BaseValidator class which inherits from the Label class – Therefore custom error messages are displayed using Label controls Validation controls that perform comparisons inherit directly from BaseCompareValidator base class

77 Using Validation Controls (Page 4) Common properties – Display property—shows the message Dynamic—space for the validation message is dynamically added to the page only if validation fails Static—space for the validation message is allocated in the page layout whether there is an error, or not None—validation message is never displayed in the browser – ErrorMessage—displayed if the value of the control is in error (extends from Text property of a Label) – ForeColor property is the color of the error message (default color is red)

78 Using Validation Controls (Page 5) Validate method performs validation on associated input control and updates the IsValid property – Page.IsValid (Boolean) indicates if the controls on the page are valid after the Page.Validate method executes The following checks if the entire form is valid Page.Validate() If Page.IsValid Then Message.Text = "Result: Valid!" Else Message.Text = "Result: Not valid!" End If

79 Using Validation Controls (Page 6) ControlToValidate property specifies the control to validate For the RegularExpressionValidator control, theValidationExpression property compares control to the regular expression – Regular Expression is a rule that describes the value using a language that describes one or more groups of characters

80 Using Validation Controls (Page 7) The ValidationExpression property – Built-in regular expressions – Regular Expression Editor – Library of sample codes Internet E-Mail Address \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* Internet URL http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)? US Phone Number \d{3}-\d{3}-\d{4} US Zip Code \d{5}(-\d{4})?

81 ASPValidateForm.aspx

82 Using Validation Controls (Page 8) The ValidationSummary control – Summarizes in one location the error messages from all validators on a Web page – Properties: DisplayMode—error messages displays as a list (List), a bulleted list (BulletList), or a single paragraph (SingleParagraph) ShowSummary—shows the entire list ShowMessageBox—displays errors in an alert box HeaderText—a heading message displayed prior to the error listing

83 ASPValidationSummary.aspx

84 Binding Web Form Controls to Simple Data Bind data to controls – Assign a DataSource – Call the DataBind method Group together controls – RadioButtonList controls—group RadioButtons – CheckboxList controls—group CheckBox controls Set group properties – RepeatDirection property—displayed horizontally or vertically – RepeatLayout property—use table or paragraph tags

85 Binding RadioButtonLists to ArrayLists (Page 1) An ArrayList is a type of array – Size dynamically increases as required – Declared using Dim, the array name, and keyword New, and ArrayList at the type Properties and Methods – Capacity—the number of items the list can hold zero-based - counting of items starts at 0 and not 1; default capacity of 16 – Count—determines the number of items in the list – Add method—used to add items to the list – SelectedItem—determines which element is selected

86 Binding RadioButtonLists to ArrayLists (Page 2) Add items to array list and populate RadioButtonList … AR1.Add("Sports in Ireland") RBL.DataSource = AR1 RBL.DataBind() Retrieve values using SelectedItem property Dim strResult As String strResult = " You selected: " If RBL.SelectedIndex > -1 Then strResult += RBL.SelectedItem.Text End If lblTopics.Text = strResult

87 Binding CheckBoxLists to HashTables (Page 1) Items are added using a key and value pair Declare using keyword Dim, HashTable name, keyword New, and Hash(n) as type (n is table size) – Add method adds items to the HashTable. – Use the key to retrieve the value for a particular item You must specify the key and value: – DataValueField is used to create the value – DataTextField is used to create the text displayed

88 Binding CheckBoxLists to HashTables (Page 2) Add a value to a HashTable (key, value) Populate the CheckBoxList and bind data to control – Notice that the key or value may be displayed; in this example, the value isdisplayed: If Not Page.IsPostBack Then Dim HS1 As New HashTable(5) … HS1.Add(5, "Sports in Ireland") CBL.DataSource = HS1 CBL.DataTextField = "Value" CBL.DataValueField = "Key" CBL.DataBind() End If

89 Binding CheckBoxLists to HashTables (Page 3) Loop through each control in the list and read values using the Boolean Selected property: If CBL.SelectedIndex > -1 Then strResult = _ "You selected the following categories: " Dim i As Integer For i = 0 To CBL.Items.Count - 1 If CBL.Items(i).Selected Then strResult += CBL.Items(i).Text + " " End If Next Else strResult = "You did not select a category." End If lblTopics.Text = strResult

90 ASPRadioButtonList.aspx

91 ASPDBCheckboxList.aspx

92


Download ppt "Web Forms and Server Controls ASP.NET. Using HTML Server Controls All HTML tags can be changed into server-side tags using the attribute and value runat="server""

Similar presentations


Ads by Google