Subscribe

RSS Feed (xml)

Validating User Form Input in ASP.NET

ASP.NET ships with a suite of validation controls that make form validation a relatively
simple process for most rules.These include the following controls:
n RequiredFieldValidator
n RangeValidator
n CompareValidatior
n RegularExpressionValidator
n CustomValidator
In addition, display of error messages is eased by the use of the ValidationSummary
control.The following code sample demonstrates each of these validators and includes
comments describing their various properties where it may not be immediately obvious.
<%@ Page language=”vb” %>
<%@ Import namespace=”System.Web.UI.WebControls” %>
<script runat=”server”>
Public Sub button1_Click(sender As Object, e As System.EventArgs)
Label1.Text = “Hello, the time is now “ & DateTime.Now.ToLongTimeString() & _
“<br>Page.IsValid = “ & Page.IsValid
End Sub
Public Sub ServerValidate(sender As Object, args As ServerValidateEventArgs)
Dim num As Integer = Int32.Parse(args.Value)
If num Mod 2 = 0 Then
args.IsValid = True
Else
args.IsValid = False
End If
End Sub
</script>
<script type=”text/javascript”>
function isEven(oSrc, args){
//var _sqrt = Math.round(Math.sqrt(args.Value));
args.IsValid = (args.Value % 2 == 0);
}
</script>
<html>
<body>
<form method=”post” runat=”server”>
<table>
<tr>
<td>
RequiredFieldValidator
</td>
<td>
<asp:textbox id=”TextBox1” runat=”server” />
</td>
<td width=”400”>
<!—
These RequiredFieldValidator properties are common to all validators.
ControlToValidate links the validator to another Web control and is
required for all validators.
Text is displayed where the validator is located when there is a
ValidationSummary.
ErrorMessage is displayed in the ValidationSummary.
Display can be Static or Dynamic.
When it is static, the browser will hold
space for the validator’s output.
When it’s Dynamic, the browser will resize as
needed when the validator is triggered.
In addition, you can specify a value for InitialValue, which is useful
if you have a form element with some default text in it, such as
“Enter a value”. Note that if a non-blank value is specified for
InitialValue,
a blank value will then be considered valid.
—>
<asp:RequiredFieldValidator id=”TextBox1Required”
runat=”server” ControlToValidate=”TextBox1”
Text=”*” Display=”Static”
ErrorMessage=”RequiredFieldValidator field is required.” />
</td>

</tr>
<tr>
<td>
RangeValidator
</td>
<td>
<asp:textbox id=”TextBox2” runat=”server” />
<br>
</td>
<td>
<!—
The RangeValidator supports properties
MinimumValue and MaximumValue, which are self-explanatory, and
Type, which must be one of Currency, Date, Double, Integer, or String.
—>
<asp:RangeValidator id=”TextBox2Range”
ControlToValidate=”TextBox2” MinimumValue=”2”
MaximumValue=”5” Type=”Integer” Text=”Invalid!”
runat=”server” Display=”Dynamic”
ErrorMessage=”RangeValidator value must be between 2 and 5 inclusive.” />
</td>
</tr>
<tr>
<td>
CompareValidator: Integer Field
</td>
<td>
<asp:textbox id=”TextBox3” runat=”server” />
</td>
<td>
<!—
The CompareValidator adds the following properties:
Operator - can be a comparison operator, such as Equal, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, NotEqual
or can be DataTypeCheck as it is here.
DataTypeCheck will simply validate that the value of the
ControlToValidate is of the specified type.
Not shown is the ValueToCompare, which can be used to specify
a particular value to which the ControlToValidate should be compared.
Not used for DataTypeCheck.
—>
<asp:CompareValidator id=”TextBox3CompareInteger”
ControlToValidate=”TextBox3” Operator=”DataTypeCheck”
Type=”Integer” Text=”!” Display=”Dynamic”
ErrorMessage=”CompareValidator - Value must be an integer.”
runat=”server” />

</td>
</tr>
<tr>
<td>
CompareValidator: One Integer field less than other
</td>
<td>
<asp:textbox id=”TextBox4” runat=”server” />
<br>
<asp:textbox id=”TextBox5” runat=”server” />
</td>
<td>
<!—
The CompareValidator can be used to compare the values of two controls by
specifying a control in the ControlToCompare property. Note that
ControlToCompare
and ValueToCompare cannot both be set for a particular control.
—>
<asp:CompareValidator id=”TextBox45Compare”
ControlToValidate=”TextBox4” ControlToCompare=”TextBox5”
Operator=”LessThan” Type=”Integer” Text=”A must be < B”
runat=”server” Display=”Dynamic”
ErrorMessage=”CompareValidator: First field must be less than second field.” />
</td>
</tr>
<tr>
<td>
RegularExpressionValidator
</td>
<td>
<asp:textbox id=”TextBox6” runat=”server” />
<br>
</td>
<td>
<!—
ValidationExpression refers to a valid regular expression.
The beginning of string (^)
and end of string characters ($) are optional for these expressions
and are always assumed by
the control. You’ll find many sample regular expressions at
http://regexlib.com/.
Note that the Text property can also be set by placing a value between
the opening and closing
tags of a validator, as shown below.
—>

<asp:RegularExpressionValidator id=”TextBox6Regex”
runat=”server” ControlToValidate=”TextBox6”
ValidationExpression=”^\d{5}$” Display=”Dynamic”
ErrorMessage=”RegularExpression:Zip code must be 5 numeric digits”>
*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
CustomValidator: Even Number
</td>
<td>
<asp:textbox id=”TextBox7” text=”3” runat=”server” />
<br>
</td>
<td>
<!—
The CustomValidator supports one property and one event. The property
is ClientValidationFunction and the event is ServerValidate. You
can specify a client-side function with the former property which will
be used for client-side validation, and you can handle the
ServerValidate event for server-side validation. The client and server
functions must follow the design shown in the <script> blocks at
the top of this listing.
—>
<asp:CustomValidator id=”TextBox7Custom” runat=”server”
ControlToValidate=”TextBox7”
OnServerValidate=”ServerValidate” Display=”Dynamic”
ErrorMessage=”Must be an even number!”
ClientValidationFunction=”isEven”>
*</asp:CustomValidator>
</td>
</tr>
</table>
<p>
<asp:Button id=”Button1” onClick=”Button1_Click”
text=”Save” runat=”server” />
<p>
<asp:Label id=”Label1” runat=”server” />
<p>
<!—
The ValidationSummary control supports properties that control how it is
displayed, such as HeaderText, which controls the header.
DisplayMode must be one of BulletList, List, or SingleParagraph.
ShowMessageBox, when true, will display a JavaScript Alert with the
contents of the validation summary.

ShowSummary, when false, will hide the summary on the page.
This can be useful if no
errors are to be output to the browser but the summary is to be logged,
for instance.
—>
<asp:ValidationSummary ID=”ValidationSummary1” runat=”server”
HeaderText=”Error in the following field(s):”
DisplayMode=”BulletList” />
</form>
</body>
</html>

Remember that all validators run both client-side and server-side, and that you should
always check Page.IsValid to ensure that its value is True before you perform any
operations on the data that was submitted.

Displaying a Calendar in a Web Form in ASP.NET

You can use the CalendarWeb Control to display a calendar on a page or as a selection
tool on a form. Its sub-elements appearance can all be set using its properties.To display
a calendar with notes on some days:
<script runat=”server”>
Sub PrettyCalendar_OnDayRender (Sender As Object, _
e As System.Web.UI.WebControls.DayRenderEventArgs)
If e.Day.Date = Today Then
‘Add a carriage return
e.Cell.Controls.Add(new LiteralControl(“<br />”))
‘Add a message of the day
e.Cell.Controls.Add(new LiteralControl(“Today!”))
End If
End Sub
</script>
<form runat=”server”>
<asp:Calendar ID=”PrettyCalendar” Runat=”server”
OnDayRender=”PrettyCalendar_OnDayRender”>
<TodayDayStyle ForeColor=”Red” BackColor=”Aqua”></TodayDayStyle>
<DayStyle Font-Bold=”True” HorizontalAlign=”Left” Height=”90px”
BorderWidth=”1px” BorderStyle=”Solid” BorderColor=”Blue” Width=”100px”
VerticalAlign=”Top” BackColor=”#80FFFF”></DayStyle>
<NextPrevStyle ForeColor=”Blue”></NextPrevStyle>
<DayHeaderStyle Font-Size=”Large” Font-Bold=”True” BorderWidth=”1px”
ForeColor=”Brown” BorderStyle=”Solid” BorderColor=”Black” Width=”100px”
BackColor=”#00C0C0”></DayHeaderStyle>
<TitleStyle Font-Size=”Large” Font-Bold=”True” BorderWidth=”1px”
BorderStyle=”Solid” BorderColor=”Black” BackColor=”#80FFFF”></TitleStyle>
<WeekendDayStyle BackColor=”#C0C0FF”></WeekendDayStyle>
</asp:Calendar>
</form>
To use a calendar for user input on a Web Form:
<%@ Page Language=”VB” Explicit=”true” Strict=”true” %>
<HTML>
<body>
<script runat=”server”>
Sub Page_Load(Sender As object, e As EventArgs)
If Not IsPostBack Then
DepartureDate.SelectedDate = System.DateTime.Today
End If
End Sub
Sub SearchButton_Click(Sender As object, e As EventArgs)
If DepartureDate.SelectedDate <= System.DateTime.Today Then
ResultLabel.Text = _
“You must selected a Departure Date in the future.”
ElseIf(ReturnDate.SelectedDate < DepartureDate.SelectedDate)
ResultLabel.Text = “Return Date must follow the Departure Date.”
Else
ResultLabel.Text = “Departing on “ & _
DepartureDate.SelectedDate.ToShortDateString() & _
“ and returning on “ & _
ReturnDate.SelectedDate.ToShortDateString()
End If
End Sub
</script>
<form runat=”server” ID=”Form1”>
<h1>Find a Flight</h1>
<table>
<tr>
<td>Departure Date</td>
<td><asp:Calendar ID=”DepartureDate” Runat=”server”>
<DayStyle Font-Size=”X-Small”></DayStyle>
<TitleStyle Font-Bold=”True”></TitleStyle>
</asp:Calendar></td>
</tr>
<tr>
<td>Return Date</td>
<td><asp:Calendar ID=”ReturnDate” Runat=”server”>
<DayStyle Font-Size=”X-Small”></DayStyle>
<TitleStyle Font-Bold=”True”></TitleStyle>
</asp:Calendar></td>
</tr>
</table>
<asp:Button ID=”SearchButton” Runat=”server”
Text=”Search” OnClick=”SearchButton_Click” />
<br>
<asp:Label ID=”ResultLabel” Runat=”server” />
</form>
</body>
</HTML>

You can extend the Calendar control a number of ways, such as allowing users to select
certain weeks or months or ranges of dates. It can be used to display events on certain
dates, and its appearance can be controlled by its properties or through the use of
Cascading Style Sheets. It does not support the use of the standard validation controls,
but a CustomValidator can be used to validate a calendar, if necessary.

Selectively Hiding or Revealing Portions of a Web Form Programmatically in ASP.NET

Toggle the Visible property of controls that inherit from System.Web.UI.Control.The
ASPX page:
<html>
<body>
<form runat=”server”>
<asp:panel id=”pnlSample” runat=”server”>
<asp:Label id=”lblSample” runat=”server” Text=”Sample Text” />
</asp:panel>
<asp:button runat=”server” id=”btnToggle” Text=”Toggle Panel Visibility”
OnClick=”btnToggle_Click” />
</form>
</body>
</html>
In <script runat=”server” /> block or codebehind:
Sub btnToggle_Click(sender as object, e as EventArgs)
pnlSample.Visible = Not pnlSample.Visible
End Sub

The Panel control used here can contain other controls.When setting the Visible property
of the Panel, the change is reflected through the controls within the panel as well.
Because all the Web Server Controls inherit from System.Web.UI.Control, you can utilize
the Visible property of each of them.This property can be set to True or False.

Creating a Scrolling Table within a Web Form in ASP.NET

Using Cascading Style Sheets, it is simple to create a scrolling region inside a Web Form.
In the ASPX page:
<table border=”1” bgcolor=”#EEEEEE”>
<tr>
<td>Query Results:</td>
<td><div style=”overflow-y:scroll; height=40;”>
<table bgcolor=”#FFFFFF”>
<tr bgcolor=”#CCCCCC”>
<td>First Name</td><td>Last Name</td>
</tr>
<tr>
<td>Steve</td><td>Smith</td>
</tr>
<tr>
<td>Rob</td><td>Howard</td>
</tr>
<tr>
<td>ASPAlliance</td><td>Team</td>
</tr>
</table>
</div>
</td>
</tr>
</table>

This technique is not supported by all browsers, but will work with Internet Explorer
4.0 and later and should work with Netscape 6.0 and later. The overflow property has a

number of options that you can set that many ASP.NET developers are unaware of.
These options can provide very powerful benefits for your Web Form presentation.

Submitting Data to Another Page Using ASP.NET

Submit the data directly from the client using a form post with the action attribute
specifying the target Web page.The ASPX page is as follows:
<form method=”post” action=”0104asp.asp”>
Price: <Input type=”text” name=”Price” value=”22.50” /><br>
Quantity: <Input type=”text” name=”Quantity” value=”4” /><br>

<Input type=”submit” value=”Submit Entire Form” />
</form>
Submit the data through the query string using a redirect on the server.You do this after
the client has posted back to the server with the data to be appended to the query
string.
The ASPX page is as follows:
<form runat=”server”>
Price: <asp:TextBox Runat=”server” ID=”Price” Text=”22.50” /><br>
Quantity: <asp:TextBox Runat=”server” ID=”Quantity” Text=”4” /><br>
<asp:Button Runat=”server” ID=”SubmitButton”
Text=”Postback and Redirect” OnClick=”SubmitButton_Click”/><br>
<asp:Button Runat=”server” ID=”WebRequestButton”
Text=”Submit by Web Request” OnClick=”WebRequestButton_Click”/>
<asp:Label Runat=”server” ID=”WebResponseLabel”/>
</form>
In <script runat=”server” /> block or codebehind:
Private Sub SubmitButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Response.Redirect(“0104asp.asp?Price=” & Price.Text & _
“&Quantity=” & Quantity.Text)
End Sub


You create a Web request to post to the target Web page from within the postback and
then display this information to the client, all within the same client-server round trip. In
<script runat=”server” /> block or codebehind:
Private Sub WebRequestButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim RequestUrl As String =
Request.Url.GetLeftPart(System.UriPartial.Authority) & _
Request.ApplicationPath & “/0104asp.asp”
Dim Post As String = “Price=” & Price.Text & _
“&Quantity=” & Quantity.Text
Dim Writer As StreamWriter = Nothing
Dim WebRequestObject As HttpWebRequest
Dim sr As StreamReader
Dim WebResponseObject As HttpWebResponse
Try
WebRequestObject = CType(WebRequest.Create(RequestUrl), HttpWebRequest)
WebRequestObject.Method = “POST”
WebRequestObject.ContentType = “application/x-www-form-urlencoded”

WebRequestObject.ContentLength = Post.Length
Writer = New StreamWriter(WebRequestObject.GetRequestStream())
Writer.Write(Post)
Writer.Close()
WebResponseObject = CType(WebRequestObject.GetResponse(),
HttpWebResponse)
sr = New StreamReader(WebResponseObject.GetResponseStream)
WebResponseLabel.Text = sr.ReadToEnd
Finally
Try
sr.Close()
Catch
End Try
Try
WebResponseObject.Close()
WebRequestObject.Abort()
Catch
End Try
End Try
End Sub

There are three ways to submit data to another Web page:
1. Form post from the client
2. Postback to the server followed by redirect
3. Postback to the server and create an HttpWebRequestThe first method involves a form post from the client.The form has the action attribute
set to the target Web page.When the client clicks the Submit button, the entire form
is posted to the target Web page directly from the client.The disadvantage to this
method is that the data cannot be manipulated on the server before being posted to the
target page.

The second method involves posting back to the server. During the postback event,
the selected data is validated and then attached to the query string of the target Web
page.The target Web page then extracts the data from the query string.The disadvantage
of this method is that the data is visible in the query string and has size restrictions.
The third method involves creating an HttpWebRequest to submit the data to the target
Web page and then receive the response immediately.This all occurs within the single
postback, thus eliminating the redirect. The response from the target Web page can then be parsed and displayed to the
client.

Dynamically Adding Literal Text or HTML to a Web Form in ASP.NET

Use the System.Web.UI.WebControls.Literal control to place literal text anywhere
on a Web Form.The ASPX page is as follows:

<html>
<head>
<title><asp:Literal id=”litTitle” runat=”server” /></title>
</head>
<body></body>
</html>
In <script runat=”server” /> block or codebehind:
Sub Page_Load(sender As Object, e As EventArgs)
litTitle.Text = “This is my page title.”
End Sub

The easiest way to place some content on a Web page when you want to have absolute
control over the formatting (for example, you don’t want your text wrapped in a <div>
tag or in other HTML tags) is to use the Literal control in the System.Web.UI.
WebControls namespace. Another option that you can use is data-binding, which you
use by adding <%# VariableName %> to the page and ensuring that Me.DataBind() is
called somewhere in the page’s execution (typically during Page_Load). Usually the
Literal is a better solution, however, because data-binding the page will force all the
controls on the page to data-bind as well, and this can cause unexpected results or inefficient
use of your controls.You can also use the LabelWeb Server Control to display
dynamic text.

Creating an ASP.NET Page

To create an ASP.NET page (a Web Form), you simply create a file with an .ASPX
extension and place it in a Web folder.The ASPX page is as follows:
<%@ Page Language=”vb” Explicit=”true” Strict=”true” %>


A simple ASP.NET Page. All @Page attributes are optional.
The ASP.NET engine will process any ASPX page, even if it doesn’t contain any code,
just as is done in ASP.There are about 20 optional parameters you can set in the Page
directive.The three listed in this example (Language, Explicit, and Strict) are optional,
but are strongly recommended. If Language is omitted, the default language specified
in the web.config file is used.Two additional items that are worth mentioning are the
Src and Codebehind attributes. Src is used to specify a file to use for the codebehind
class when the page is first requested.The class found at this location is compiled the first
time the page is requested.The Codebehind attribute is similar—it is used at compile
time by Visual Studio .NET to maintain a link between ASPX pages and their codebehind
classes. Do not use both the Src and Codebehind attributes in a Visual Studio
.NET project or you will get a duplicate class error; the same class is compiled and referenced
twice. In addition to Src or Codebehind, you must also specify the Inherits
attribute in order to use a codebehind class.

Variety in the Web World