The disconnected nature of Web browsers
presents many obstacles when developing Web-based applications. For
instance, loading data into the browser involves a round-trip to
the server to retrieve it. There are various approaches to loading
data, with each platform providing its own approach. The inclusion
of Web Controls with ASP.NET provides another alternative.
Web Controls
ASP.NET Web Controls offer a robust set of
controls to build Web-based applications. With Web Controls,
Microsoft reworked HTML according to their design. These controls
are analogous to HTML controls.
Here’s a sample Web Control with the HTML tag
presented first:
<input type=”text” name=”FirstName” />
This is the equivalent Web Control:
<asp:TextBox id=”FirstName”
runat=”server”></asp:TextBox>
All Web Controls require the following to
function properly:
- They’re placed within a <form runat=”server”> tag.
- They require id and runat=”server” attributes.
- They all begin with the asp: prefix.
While Web Controls are Microsoft’s version of
HTML elements, there are more Web Controls than corresponding HTML
elements. They can be divided into these categories: basic
(textbox, listbox, etc.), validation, data, and user (custom).
Now let’s take a look at using Web Controls to
add search functionality to a Web form. The following code snippet
uses Web Controls to add search functionality (the user interface)
to a form. Only the search portion of the form is included; but, in
reality, a DataGrid would be present as well and the search would
interact with it.
<%@ Page language=”c#” Trace=”False”
Codebehind=”WebControlEvents.aspx.cs”
AutoEventWireup=”false” Inherits=”BulderExamples.WebControlEvents”
%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”
>
<html><head>
<title>Builder.com Web Control Example</title>
</head>
<form id=”frmBuilderWebControlExample” method=”post”
runat=”server”>
<table id=”tblReportSearchControl” cellSpacing=”0″
cellPadding=”0″ border=”0″>
<tr><td style=”WIDTH: 179px; HEIGHT: 119px”>
<asp:radiobuttonlist id=”rblRequest” runat=”server”
Width=”300px”
RepeatColumns=”2″ AutoPostBack=”True”
OnSelectedIndexChanged=”rblRequest_SelectedIndexChanged”>
<asp:ListItem Value=”0″ Selected=”True”>Started
On</asp:ListItem>
<asp:ListItem Value=”1″>Started
Between</asp:ListItem>
<asp:ListItem Value=”2″>Completed
On</asp:ListItem>
<asp:ListItem Value=”3″>Completed
Between</asp:ListItem>
</asp:radiobuttonlist>
</td><td style=”WIDTH: 170px; HEIGHT: 119px”
align=”center”>
<asp:label id=”lblStartDate” Font-Bold=”True”
runat=”server”>Start
Date</asp:label><asp:textbox id=”txtStartDate”
runat=”server”></asp:textbox>
</td><td style=”HEIGHT: 119px” align=”center”>
<asp:label id=”lblAnd” runat=”server” Visible=”False”> and
</asp:label>
</td><td style=”HEIGHT: 119px” align=”center”>
<asp:label id=”lblEndDate” Font-Bold=”True” runat=”server”
Visible=”False”>End
Date</asp:label><asp:textbox id=”txtEndDate”
runat=”server”
Visible=”False”></asp:textbox>
</td></tr>
<tr><td align=”center” colSpan=”4″>
<asp:button id=”btnSearch” Font-Bold=”True”
runat=”server”
Text=”Search”></asp:button>
</td></tr>
</table></form></body></html>
This code:
-
Presents a radio button control that allows the user to choose how
to search. They may search by Start and Complete dates, or an
interval may be used. -
The radio button selection shows/hides TextField and Label controls
based upon the value selected. For example, both the Start and End
date controls are displayed when an interval is chosen, and only
the Start date is displayed for the option using only one
value. -
The Visible property of the TextBox and Label controls is used to
show/hide them.
The codebehind file for this page would contain
the following code:
public void rblRequest_SelectedIndexChanged(object
sender, EventArgs e) {
switch (rblRequest.SelectedIndex) {
case 0 :
lblAnd.Visible = false;
txtEndDate.Visible = false;
txtStartDate.Visible = true;
lblEndDate.Visible = false;
lblStartDate.Text = “Date”;
break;
case 1 :
lblAnd.Visible = true;
txtEndDate.Visible = true;
txtStartDate.Visible = true;
lblEndDate.Visible = true;
lblEndDate.Text = “End Date”;
lblStartDate.Visible = true;
lblStartDate.Text = “Start Date”;
break;
case 2 :
lblAnd.Visible = false;
txtEndDate.Visible = false;
txtStartDate.Visible = true;
lblEndDate.Visible = false;
lblStartDate.Visible = true;
lblStartDate.Text = “Date”;
break;
case 3 :
lblAnd.Visible = true;
txtEndDate.Visible = true;
txtStartDate.Visible = true;
lblEndDate.Visible = true;
lblEndDate.Text = “End Date”;
lblStartDate.Visible = true;
lblStartDate.Text = “Start Date”;
break;
default :
lblAnd.Visible = false;
txtEndDate.Visible = false;
txtStartDate.Visible = true;
lblEndDate.Visible = false;
lblStartDate.Visible = true;
lblStartDate.Text = “Start Date”;
break;
} }
private void btnSearch_Click(object sender, EventArgs e) {
// Conduct search
}
public string getStartDate() {
return txtStartDate.Text;
}
public string getEndDate() {
return txtEndDate.Text;
}
public string getSelection() {
return this.rblRequest.SelectedValue.ToString();
}
You should notice that each Web Control–and
the Web form itself–includes the runat=”Server” attribute. This
tells the server to process the controls and their respective
events on the server. The AutoPostBack attribute of the
RadioButtonList control is set to true, so the server processes
each event fired by the control–the request is posted back to the
server (the form is submitted). The OnSelectedIndexChange
attributed signals what method to use to process the event.
VB.NET may easily be used instead of C#. Here is the VB.NET version
of the code:
Public Sub rblRequest_SelectedIndexChanged(ByVal
sender As Object, ByVal e As
EventArgs)
Select Case (rblRequest.SelectedIndex)
Case 0
lblAnd.Visible = False
txtEndDate.Visible = False
txtStartDate.Visible = True
lblEndDate.Visible = False
lblStartDate.Text = “Date”
Case 1
lblAnd.Visible = True
txtEndDate.Visible = True
txtStartDate.Visible = True
lblEndDate.Visible = True
lblEndDate.Text = “End Date”
lblStartDate.Visible = True
lblStartDate.Text = “Start Date”
Case 2
lblAnd.Visible = False
txtEndDate.Visible = False
txtStartDate.Visible = True
lblEndDate.Visible = False
lblStartDate.Visible = True
lblStartDate.Text = “Date”
Case 3
lblAnd.Visible = True
txtEndDate.Visible = True
txtStartDate.Visible = True
lblEndDate.Visible = True
lblEndDate.Text = “End Date”
lblStartDate.Visible = True
lblStartDate.Text = “Start Date”
Case Else
lblAnd.Visible = False
txtEndDate.Visible = False
txtStartDate.Visible = True
lblEndDate.Visible = False
lblStartDate.Visible = True
lblStartDate.Text = “Start Date”
End Select
End Sub
Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As
EventArgs)
‘ Conduct search
End Sub
Public Function getStartDate() As String
Return txtStartDate.Text
End Function
Public Function getEndDate() As String
Return txtEndDate.Text
End Function
Public Function getSelection() As String
Return rblRequest.SelectedValue.ToString()
End Function
This code may be easily combined with a
DataGrid control to provide the necessary search functionality. The
problem with this approach is the roundtrips to the server. The
server is called each time the radio button is changed, so
performance becomes an issue. This is especially true if the form
contains other items like a DataGrid control that is reloaded each
time the form is submitted (you may avoid this by utilizing the
IsPostBack method). The opposite approach utilizes client-side code
via JavaScript and HTML elements.
The HTML and JavaScript approach
Utilizing HTML elements and JavaScript reduces
the server load. JavaScript allows the clicking of a radio button
to be processed without a call to the server. It may be combined
with DHTML to easily show/hide HTML elements. The best way to
demonstrate its usefulness is with an example. The following code
includes these elements:
-
A JavaScript function to show or hide specific DHTML elements. In
particular, it manipulates a label and text box corresponding to
the search end date. This function is named showHide. -
A JavaScript function (called setSearchFields) to set up the fields
upon loading of the form. -
The Web form contains HTML elements instead of ASP.NET Web
Controls. -
The HTML radio button elements are assigned the showHide function
to their onClick event. -
ASP.NET functions are used to populate the HTML controls when the
form is loaded. This allows the form to retain its values when/if
the page is posted back to the server. These functions utilize the
form array of values in the Request object. - The only ASP.NET Web Control utilized is the search button.
Here’s the code:
<%@ Page language=”c#” Trace=”False”
Codebehind=”BuilderControlsTest.aspx.cs”
AutoEventWireup=”false” Inherits=”BuilderExamples.Report”
%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”
>
<html><head>
<title>Builder.com Web Control Example</title>
</head>
<script language=”javascript”>
function showHide(h) {
if (document.all) { // Internet Explorer
if (h==’s’) {
eval(“document.all.lblAnd.style.visibility=’visible’;”);
eval(“document.all.endDate.style.visibility=’visible’;”);
}
if (h==’h’) {
eval(“document.all.lblAnd.style.visibility=’hidden’;”);
eval(“document.all.endDate.style.visibility=’hidden’;”);
} } else { // Netscape
if (h==’s’) {
eval(“document.layers[‘lblAnd’].visibility=’show’;”);
eval(“document.layers[‘endDate’].visibility=’show’;”);
}
if (h==’h’) {
eval(“document.layers[‘lblAnd’].visibility=’hide’;”);
eval(“document.layers[‘endDate’].visibility=’hide’;”);
} } }
function setSearchFields() {
var doc = document.forms[0];
if (doc.r1[0].checked == true) {
showHide(‘h’);
} else if (doc.r1[1].checked == true) {
showHide (‘h’);
} else if (doc.r1[2].checked == true) {
showHide (‘s’);
} else if (doc.r1[3].checked == true) {
showHide (‘s’);
} else {
showHide (‘h’);
} }
</script></head>
<body ms_positioning=”FlowLayout”>
<form id=”frmBuilderHTMLJavaScriptExample” method=”post”
runat=”server”>
<table id=”tblReportSearch” cellSpacing=”0″ cellPadding=”0″
border=”0″>
<tr><td style=”WIDTH: 160px; HEIGHT: 60px”>
<input onclick=”showHide(‘h’)” <%= getRadioStatus(0) %>
type=”radio” value=”0″
name=”r1″>Started On
<input onclick=”showHide(‘h’)” <%= getRadioStatus(1) %>
type=”radio” value=”1″
name=”r1″>Completed On
<input onclick=”showHide(‘s’)” <%= getRadioStatus(2) %>
type=”radio” value=”2″
name=”r1″>Started Between
<input onclick=”showHide(‘s’)” <%= getRadioStatus(3) %>
type=”radio” value=”3″
name=”r1″>Completed Between
</td>
<td style=”WIDTH: 109px; HEIGHT: 60px” align=”center”>
<div id=”lblStartDate”>Start Date</div>
<input id=”txtStartDate” type=”text” name=”txtStartDate”
value=”<%=
getStartDate() %>” size=”8″>
</td><td style=”WIDTH: 5px; HEIGHT: 60px”
align=”center”>
<span id=”lblAnd”>and </span>
</td><td style=”WIDTH: 139px; HEIGHT: 60px”
align=”center”>
<span id=”endDate”>
<div id=”lblEndDate”>End Date</div>
<input id=”txtEndDate” type=”text” align=”center”
name=”txtEndDate” value=”<%=
getEndDate() %>” size=”8″>
</span>
</td></tr>
<tr><td colSpan=”4″ align=”center”>
<asp:button id=”btnSearch” runat=”server”
Font-Bold=”True”
Text=”Search”></asp:button>
</td></tr></table>
The codebehind file for this page would contain
the following code:
private void btnSearch_Click(object sender,
EventArgs e) {
// Conduct search
}
public string getStartDate() {
if (Request.Form[“txtStartDate”] == null) {
return ” “;
} else if (Request.Form[“txtStartDate”].Trim() == “”) {
return ” “;
} else {
return Request.Form[“txtStartDate”];
} }
public string getEndDate() {
if (Request.Form[“txtEndDate”] == null) {
return ” “;
} else if (Request.Form[“txtEndDate”].Trim() == “”) {
return ” “;
} else {
return Request.Form[“txtEndDate”];
} }
public string getSelection() {
return Request.Form[“r1”];
}
public string getRadioStatus(int index) {
string rValue=””;
switch (index){
case 0 :
if (getSelection() == “0”) {
rValue = “CHECKED”;
} else {
if ((getSelection() != “1”) & (getSelection() != “2”) &
(getSelection() !=
“3”)) {
rValue = “CHECKED”;
} }
break;
case 1 :
if (getSelection() == “1”) {
rValue = “CHECKED”;
}
break;
case 2 :
if (getSelection() == “2”) {
rValue = “CHECKED”;
}
break;
case 3 :
if (getSelection() == “3”) {
rValue = “CHECKED”;
}
break;
}
return rValue;
}
</script>
As with the first example, the ASP.NET code
portion may utilize VB.NET instead of C#:
Private Sub btnSearch_Click(ByVal sender As Object,
ByVal e As EventArgs)
‘ Conduct search
End Sub
Public Function getStartDate() As String
Dim rValue As String
If (Request.Form(“txtStartDate”) Is Nothing) Then
getStartDate = ” “
ElseIf (Request.Form(“txtStartDate”).Trim() = “”) Then
getStartDate = ” “
Else
getStartDate = Request.Form(“txtStartDate”)
End If
End Function
Public Function getEndDate() As String
If (Request.Form(“txtEndDate”) Is Nothing) Then
getEndDate = ” “
ElseIf (Request.Form(“txtEndDate”).Trim() = “”) Then
getEndDate = ” “
Else
getEndDate = Request.Form(“txtEndDate”)
End If
End Function
Public Function getSelection() As String
getSelection = Request.Form(“r1”)
End Function
Public Function getRadioStatus(ByVal index As Integer) As
String
Dim rValue As String
Select Case (index)
Case 0
If (getSelection() = “0”) Then
rValue = “CHECKED”
Else
If ((getSelection() <> “1”) And (getSelection() <>
“2”) And (getSelection() <>
“3”)) Then
rValue = “CHECKED”
End If
End If
Case 1
If (getSelection() = “1”) Then
rValue = “CHECKED”
End If
Case 2
If (getSelection() = “2”) Then
rValue = “CHECKED”
End If
Case 3
If (getSelection() = “3”) Then
rValue = “CHECKED”
End If
End Select
Return rValue
End Function
Now it’s your choice
The approach utilized in your application
depends upon the situation. An intranet application may not require
the performance boost realized by client-side processing. An
Internet application will be a different story due to the fact that
users may be accessing the site via dialup, and the server load
will vary depending on the size of the user community.
TechRepublic’s free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!