0% found this document useful (0 votes)
15 views

Lecture 13, 14, 15 - ASP.NET (Part 2)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lecture 13, 14, 15 - ASP.NET (Part 2)

Uploaded by

ahihihi.0602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

C# 6 and the .NET 4.

6 Framework

Chapter 32 - ASP.NET Web Controls,


Master Pages, and Themes
Outline
• Understanding the Nature of Web Controls
• The Control and Web Control Base Classes
• Major Categories of Web Forms Controls
• Building the Web Forms Cars Web Site
• The Role of the Validation Controls
• Working with Themes
Understanding the Nature of Web
Controls
• The web controls extremely helpful in that
– They generate the necessary HTML for the requesting
browser
– They expose a set of events that may be processed on the
web server
– Each control has a corresponding class, it can be
manipulated in an OO manner
• The *.aspx file and the *.cs file
– When you edit a control in *.aspx file, you would edit the
control with property/value pairs
– This declaration of a web control eventually becomes a
member variable in the code behind
– So we can interact with this member in the *.cs code
The *.aspx file and the *.cs file
<asp:TextBox ID="txtNameTextBox" runat="server" BackColor="#C0FFC0"
BorderStyle="Dotted" BorderWidth="3px">Enter Your Name</asp:TextBox> 1

protected void btnChangeTextBoxColor_Click(object sender, EventArgs e)


{
// Change color of text box object in code.
this.txtNameTextBox.BackColor = System.Drawing.Color.DarkBlue;
} 2

1. Declare the TextBox in aspx file with some properties as key/value pair
2. Access to it in the CS code file as OO manner and properties
Understanding Server-Side Event
Handling
• When client browser communicates with the
server scripting
– Web Forms control will expose a limited set of
events
– All of which ultimately result in a postback to the
web server
– Lead to underlying, stateless HTTP request-and-
response cycle
The AutoPostBack Property
• Many of the Web Forms controls support a
property named AutoPostBack
– E.g., CheckBox, RadioButton, and TextBox controls,
etc,.
– By default, this property is set to false
– If is true, the form will post back to the server
immediately after the user interact with the control
– Can be helpful if you want to have the state of one
widget automatically populate another value for
another widget
The Control Base Classes
The WebControl Base Class
Major Categories of Web Forms
Controls
The Web Forms control library can
be broken down into several broad
categories.
Standard area of the Toolbox
Under this standard area you will find the most
frequently used controls, including Button, Label, TextBox,
and ListBox.
The Data section of the Toolbox
The Data section is where you can find a set of
controls used for data-binding operations,
including the Web Forms Chart control, which
allows you to render out graphical chart data (pie
charts, line charts) typically as the result of a data-
binding operation
The Validation section of the Toolbox
The Web Forms validation controls can be configured
to emit back blocks of client-side JavaScript that will
test input fields for valid data.
If a validation error occurs, the user will see an error
message and will not be allowed to post back to the
web server until the error is corrected.
The Navigation section of the Toolbox
This section contains a small set of controls
(Menu, SiteMapPath, and TreeView), which typically work in
conjunction with a *.sitemap file.
These navigation controls allow you to describe
the structure of a multipage site using XML
descriptions.
The Login section of the Toolbox
These controls can radically simplify how to
incorporate basic security features (password
recovery, login screens, etc.) into your web
applications.
In fact, these controls are so powerful, they will
even dynamically create a dedicated database to
store credentials (saved under the App_Data folder of
your web site) if you do not already have a
specific security database.
System.Web.UI.HtmlControls
• There are two distinct web control toolkits that ship with Web Forms
– The Web Forms controls (within the System.Web.UI.WebControls namespace)
– The System.Web.UI.HtmlControls control library
• The HTML controls are a collection of types that allow you to make use of
traditional HTML controls on a Web Forms page
– Unlike simple HTML tags, HTML controls are object-oriented entities that can be configured to
run on the server and thus support server-side event handling
– Unlike Web Forms controls, HTML controls are quite simplistic in nature and offer little
functionality beyond standard HTML tags (HtmlButton, HtmlInputControl, HtmlTable, etc.)
• The HTML controls can be useful if
– The developers can configure these HTML controls developed by others to run as server
controls (by right-clicking an HTML widget within Visual Studio)
• The HTML controls provide a public interface that mimics standard HTML
attributes
– E.g., to obtain the information within an input area, you make use of the Value property rather
than the web control-centric Text property
BUILDING THE WEB FORMS CARS
WEB SITE
The web site
• Let's build a new web site that illustrates
working with several of the controls
• Specifically, this AspNetCarsSite will illustrate
the following techniques:
– Working with master pages
– Working with site map navigation
– Working with the GridView control
– Working with the Wizard control
Working with Web Forms Master
Pages
• Many web sites provide a consistent look and feel across
multiple pages
– Master page is a Web Forms page that takes a *.master file
extension
– The ASP.NET runtime will not serve this flavor of web content
– A master page will define various content placeholder areas that
establish a region that other *.aspx files may plug into
– *.aspx files that plug their content into a master is termed a
content page
– Content pages are *.aspx files that do not define an HTML
<form> element (that is the job of the master page)
– However, as far as the end user is concerned, a request is made
to a given *.aspx file
Adding a master page

2 1

1. Right click on the project and select Add


2. Select Add New Item
3. Select Master Page
4. Keep the default name
5. Click Add
4
5
The MasterPage.master
this directive supports the same attributes as the <%@Page%> directive
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"
Inherits="MasterPage" %>
<!DOCTYPE html> ContentPlaceHolder represents the area UI widgets of
<html> the related *.aspx content file may plug into
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
The MasterPage.master
Adding a Label, an AdRotator and a TreeView
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"
Inherits="MasterPage" %>

<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<hr />
<asp:Label ID="Label1" runat="server" Text="Welcome to the ASP.NET Cars Super Site"
Font-Size="XX-Large"></asp:Label>
<asp:AdRotator ID="AdRotator1" runat="server" />
<br />
<br />
<asp:TreeView ID="TreeView1" runat="server"></asp:TreeView>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
The MasterPage.master
Adding a Sitemap
Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="" title="Welcome" description="Welcome">
<siteMapNode url="~/Default.aspx" title="Home" description="" />
<siteMapNode url="~/BuildCar.aspx" title="Build a car" description="" />
<siteMapNode url="~/Inventory.aspx" title="View inventory" description="" />
</siteMapNode>
</siteMap>
Configuring the tree view
1

1. Click on the arrow icon


2. Select New data source
3. Select Site Map
4
4. Accept the name
5. Click OK

5
Changing the tree view icons

1. Click on the arrow icon


2. Click on Auto Format 3
3. Select XP File Explorer
4
4. Click OK
Adding Breadscrum with SiteMapPath
1

1. Click on the ToolBox


2. Drag a SiteMapPath
4
3. Drop to the design/code
4. Observe the design change
The AdRotator Control
• AdRotator is to randomly display a given image at some
position in the browser
– We need to add AdvertisementFile property to point to the
source file that describes each image
– E.g., the data source could be a simple XML file named Ads.xml.
• Add an XML file named Ads.xml
– Specify a unique <Ad> element for each image you want to
display
• Each <Ad> element specifies
– The image to display (ImageUrl),
– The URL to navigate to if the image is selected (TargetUrl),
– The Mouseover text (AlternateText),
– The weight of the ad (Impressions)
Adding the Ads.xml file
Add two advertisements
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>slugbug.png</ImageUrl>
<TargetUrl>www.cars.com</TargetUrl>
<AlternateText>Your cars?</AlternateText>
<Impressions>80</Impressions>
</Ad>
<Ad>
<ImageUrl>car.png</ImageUrl>
<TargetUrl>www.carsupersite.com</TargetUrl>
<AlternateText>Like this car?</AlternateText>
<Impressions>80</Impressions>
</Ad>
</Advertisements>

We need to add the two photos


to our web project
Configuring the AdRotator
1

1. Click on the arrow icon


2. Select New data source
3. Select XML file
4. Accept the name 4
5. Click OK

5
Configuring the AdRotator

1. Click Browse
2. Select Ads.xml
3. Click OK

3
Defining the Default Content Page
1. Right click anywhere in the page
2. Select Add Content Page
3. You will see the place for you to
define Content 1 1
4. You will see the place for you to
define Content 2

4
Defining the Inventory Page
1. Right click anywhere in the page
2. Select Add Content Page
3. You will see the place for you to
define Content 1 1
4. You will see the place for you to
define Content 2
5. Please use the solution explorer to
change the name to Inventory.aspx

4
Designing the Inventory Content Page
• Please follow the steps from previous lecture
to load all current inventory to this page
– Include the InventoryDAL project to the references
– Add a GridView to Content2 content holder
– Add the method GetAll() to load data for the grid
– Configure the GetAll() method to get
– Copy the connection string from App.Config from
InventoryDAL to Web.config of this website
Adding Delete Function in
InventoryDAL
public class InventoryRepo
{
public IEnumerable<Inventory> GetAll() {
using (var context = new AutoLotEntities()) {
return context.Inventories.ToList<Inventory>();
}
}
public void Delete(int carId) {
using (var context = new AutoLotEntities()) {
Inventory inv = context.Inventories.Find(carId);
context.Inventories.Remove(inv);
context.SaveChanges();
}
}
}
Editing the columns
We will configure the table manually:
1. Click on the arrow
2. Select and add 4 BoundField and one 4
CommandField
3. Click on each of the column 2
4. Edit the column properties as the next
slide
3

1
Column Properties
Column DataField HeaderText ReadOnly SortExpression
CarId CarId Car Id True CarId
Make Make Make Make
Color Color Color Color
PetName PetName Pet Name PetName
For the command column: set ShowDeleteButton="True"
Set the DataKeyNames

1
2

1. Click on the GridView


2. Click on Properties
3. Set the DataKeyNames
Similarly
1. Set AutoGenerateColumns="False“
2. Set DeleteMethod=“Delete”
Add the Delete method into the Code
behind
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
public IEnumerable<Inventory> GetAll() {
return new InventoryRepo().GetAll();
}
public void Delete(int carId) {
new InventoryRepo().Delete(carId);
}
}
Adding Update Function in
InventoryDAL
public class InventoryRepo
{
public IEnumerable<Inventory> GetAll() {
using (var context = new AutoLotEntities()) {
return context.Inventories.ToList<Inventory>();
}
}
public void Delete(int carId) {
using (var context = new AutoLotEntities()) {
Inventory inv = context.Inventories.Find(carId);
context.Inventories.Remove(inv);
context.SaveChanges();
}
}
public void Update(Inventory inv)
{
using (var context = new AutoLotEntities()) {
Inventory curInv = context.Inventories.Find(inv.CarId);
curInv.Color = inv.Color;
curInv.Make = inv.Make;
curInv.PetName = inv.PetName;
context.SaveChanges();
}
}
}
Add Edit, Update, Cancel Command
1. Add the Edit, Update, Cancel CommandField
2. Right click on the Grid, set the UpdateMethod to Update

2
Add the Update method into the Code
behind
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
public IEnumerable<Inventory> GetAll() {
return new InventoryRepo().GetAll();
}
public void Delete(int carId) {
new InventoryRepo().Delete(carId);
}
public void Update(Inventory inv)
{
new InventoryRepo().Update(inv);
}
}
Enabling Sorting and Paging

1 2

4
4

1. Click on the GridView


2. Select Properties
3. Change the AllowPaging, AllowSorting properties to True
4. Set the PageSize to 5
Run and Observe Paging error
Update the code behind
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
public IQueryable<Inventory> GetAll() {
return new InventoryRepo().GetAll().AsQueryable<Inventory>();
}
public void Delete(int carId) {
new InventoryRepo().Delete(carId);
}
public void Update(Inventory inv) {
new InventoryRepo().Update(inv);
}
}
Enabling Filtering

1. Click on Toolbox and drag a DropDownList


2. Drop it to the Place
3. Refresh the design and observe the change
Set Properties for the DropDownList
Property Value
Id cboMake
SelectMethod GetMakes
AppendDataBoundItems True
DataTextField Make
DataValueField Make
AutoPostBack True
Add one more Item with value is “” and text is All if, so the overall code should look
like this:
<asp:dropdownlist runat="server" ID="cboMake"
AppendDataBoundItems="True" AutoPostBack="True"
DataTextField="Make" DataValueField="Make"
SelectMethod="GetMakes">
<asp:ListItem Text="All" Value=""></asp:ListItem>
</asp:dropdownlist>
Add GetMakes and Update GetAll
methods
public IEnumerable GetMakes()
{
return new InventoryRepo().GetAll().Select(x => new { x.Make }).Distinct();
}
public IQueryable<Inventory> GetAll([Control("cboMake")]string make = "")
{
InventoryRepo ir = new InventoryRepo();
return
string.IsNullOrEmpty(make) ?
ir.GetAll().AsQueryable<Inventory>() : ir.GetAll().Where(x =>
x.Make.Equals(make)).AsQueryable<Inventory>();
}

1. The parameter is marked with a name of the control (isn't necessary if


the control name matches the parameter name). This parameter will take
the value of the control when the form data is posted back. Default value
is “” (when nothing is selected).
2. If you see the Error, click on the quick-fix icon and import the namespace
Designing Build-a-Car Content Page
1. Right click anywhere in the page
2. Select Add Content Page
3. You will see the place for you to
define Content 1 1
4. You will see the place for you to
define Content 2
5. Please use the solution explorer to
change the name to BuildACar.aspx

4
Designing Build-a-Car Content Page

2
1

1. Click on Toolbox and drag a Wizard control


2. Drop it to the Place
3. Observe the Design
Designing Build-a-Car Content Page

1
3
4

1. Click on the arrow icon of the Wizard


2. Click on Add/Remove WizardStep…
3. Add 4 steps
4. Change the titles of the steps
5. Click OK

5
Designing Build-a-Car Content Page

1
1. Click on Toolbox and drag a TextBox control
2. Drop it to the Place and name it txtCarModel
3. Observe the Design
4. Similarly
1. Drag and drop a ListBox control for step 2 name it lstColors
2. Drag and drop a TextBox control for step 3 name it txtPetName
3. Drag and drop a Calendar control for step 4 name it cldDeliveryDate

3
The List box Items
<asp:ListBox ID="lstColors" runat="server" Width="237px">
<asp:ListItem>Purple</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Pea Soup Green</asp:ListItem>
<asp:ListItem>Black</asp:ListItem>
<asp:ListItem>Lime Green</asp:ListItem>
</asp:ListBox>
Add a Label to display order

1
2

1. Click on Toolbox and drag a Label control


2. Drop it to the Place and name it lblOrder
Handling the finish wizard button

1 1. Double click on the Finish button


2. Update the code for this button

2
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
lblOrder.Text = string.Format("Your {0}, {1} {2} will be delivered on {3}", txtPetName.Text,
lstColors.SelectedValue, txtCarModel.Text, cldDeliveryDate.SelectedDate.ToShortDateString());
}
References
Troelsen, A. & Japikse, P., 2015. C# 6 and the
.NET 4.6 Framework. 7th ed. Apress.

You might also like