CHAPTER 3 Using the Validation Controls // If there is an error, show it function AjaxValidatorErrormessage { alert‘Error: ‘ + message; } The AjaxValidatorEvaluateIsValid JavaScript meth
Trang 1CHAPTER 3 Using the Validation Controls
// If there is an error, show it
function AjaxValidatorError(message)
{
alert(‘Error: ‘ + message);
}
The AjaxValidatorEvaluateIsValid() JavaScript method initiates an AJAX call by calling
the WebForm_DoCallback() method This method calls the server-side validation function
associated with the AjaxValidator control When the AJAX call completes, the
AjaxValidatorResult() method is called This method updates the display of the
valida-tion control on the client
The page in Listing 3.24 illustrates how you can use the AjaxValidator control This page
handles the AjaxValidator control’s ServerValidate event to associate a custom validation
function with the control
The page in Listing 3.24 contains a form that includes fields for entering a username and
favorite color When you submit the form, the values of these fields are inserted into a
database table named Users
In Listing 3.24, the validation function checks whether a username already exists in the
database If you enter a username that already exists, a validation error message displays
The message displays in the browser before you submit the form back to the server (see
Figure 3.17)
It is important to realize that you can associate any server-side validation function with
the AjaxValidator You can perform a database lookup, call a web service, or perform a
complex mathematical function Whatever function you define on the server is
automati-cally called on the client
LISTING 3.24 ShowAjaxValidator.aspx
<%@ Page Language=”C#” %>
<%@ Register TagPrefix=”custom” Namespace=”myControls” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Configuration” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
/// <summary>
/// Validation function that is called on both the client and server
/// </summary>
protected void AjaxValidator1_ServerValidate(object source,
➥ServerValidateEventArgs args)
{
Trang 2Creating Custom Validation Controls
args.IsValid = false;
else
args.IsValid = true;
}
/// <summary>
/// Returns true when user name already exists
/// in Users database table
/// </summary>
private bool UserNameExists(string userName)
{
string conString =
WebConfigurationManager.ConnectionStrings[“UsersDB”].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(“SELECT COUNT(*)
➥FROM Users WHERE UserName=@UserName”, con);
cmd.Parameters.AddWithValue(“@UserName”, userName);
bool result = false;
using (con)
{
con.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
result = true;
}
return result;
}
/// <summary>
/// Insert new user name to Users database table
/// </summary>
protected void btnSubmit_Click(object sender, EventArgs e)
{
string conString =
WebConfigurationManager.ConnectionStrings[“UsersDB”].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(“INSERT Users (UserName,FavoriteColor)
➥VALUES (@UserName,@FavoriteColor)”, con);
cmd.Parameters.AddWithValue(“@UserName”, txtUserName.Text);
cmd.Parameters.AddWithValue(“@FavoriteColor”, txtFavoriteColor.Text);
using (con)
{
con.Open();
Trang 3txtUserName.Text = String.Empty;
txtFavoriteColor.Text = String.Empty;
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>Show AjaxValidator</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblUserName”
Text=”User Name:”
AssociatedControlID=”txtUserName”
Runat=”server” />
<asp:TextBox
id=”txtUserName”
Runat=”server” />
<custom:AjaxValidator
id=”AjaxValidator1”
ControlToValidate=”txtUserName”
Text=”User name already taken!”
OnServerValidate=”AjaxValidator1_ServerValidate”
Runat=”server” />
<br /><br />
<asp:Label
id=”lblFavoriteColor”
Text=”Favorite Color:”
AssociatedControlID=”txtFavoriteColor”
Runat=”server” />
<asp:TextBox
id=”txtFavoriteColor”
Runat=”server” />
<br /><br />
<asp:Button
id=”btnSubmit”
Text=”Submit”
Runat=”server” OnClick=”btnSubmit_Click” />
CHAPTER 3 Using the Validation Controls
Trang 4</div>
</form>
</body>
</html>
Summary
FIGURE 3.17 Using the AjaxValidator to check whether a username is unique
Summary
In this chapter, you learned how to perform form validation with the ASP.NET 4
Framework First, you were provided with an overview of all the standard validation
controls You learned how to highlight validation error messages and how to take
advan-tage of validation groups to simulate multiple forms in a single page
In the final section of this chapter, you learned how to create custom validation controls
by deriving new controls from the BaseValidator control You saw the creation of a
custom LengthValidator and AjaxValidator control
Trang 5This page intentionally left blank
Trang 6CHAPTER 4
Using the Rich Controls
IN THIS CHAPTER
Accepting File Uploads Displaying a Calendar Displaying Advertisements Displaying Different Page Views Displaying a Wizard
Displaying Silverlight Content Summary
In previous chapters we examined the ASP.NET controls
that you use in just about any application In this chapter
we examine a more specialized set of controls known
collec-tively as the rich controls.
In the first section, you learn how to accept file uploads at
your website For example, you learn how to allow users to
upload images, Microsoft Word documents, or Microsoft
Excel spreadsheets
Next, you learn how to work with the Calendar control
You can use the Calendar control as a date picker You can
also use the Calendar control to display upcoming events
(such as a meeting schedule)
We also discuss the AdRotator control This control enables
you to display banner advertisements randomly on your
website The control enables you to store a list of
advertise-ments in an XML file or a database table
Next, you learn about the MultiView control This control
enables you to hide and display areas of content on a page
You learn how to use this control to divide a page into
different tabs
In the following section, you learn about the Wizard
control, which enables you to display multistep forms This
control is useful when you need to divide a long form into
multiple subforms
Finally, you learn how to display Silverlight content on
your page Silverlight controls enable you to add rich,
inter-active media to your website You learn how to add
Silverlight content to your page and display alternative
Trang 7CHAPTER 4 Using the Rich Controls
Accepting File Uploads
The FileUpload control enables users to upload files to your web application After the file
is uploaded, you can store the file anywhere you please Normally, you store the file either
on the file system or in a database This section explores both options
The FileUpload control supports the following properties (this is not a complete list):
Enabled—Enables you to disable the FileUpload control
FileBytes—Enables you to get the uploaded file contents as a byte array
FileContent—Enables you to get the uploaded file contents as a stream
FileName—Enables you to get the name of the file uploaded
HasFile—Returns True when a file has been uploaded
PostedFile—Enables you to get the uploaded file wrapped in the HttpPostedFile
object
The FileUpload control also supports the following methods:
Focus—Enables you to shift the form focus to the FileUpload control
SaveAs—Enables you to save the uploaded file to the file system
The FileUpload control’s PostedFile property enables you to retrieve the uploaded file
wrapped in an HttpPostedFile object This object exposes additional information about
the uploaded file
The HttpPostedFile class has the following properties (this is not a complete list):
ContentLength—Enables you to get the size of the uploaded file in bytes
ContentType—Enables you to get the MIME type of the uploaded file
FileName—Enables you to get the name of the uploaded file
InputStream—Enables you to retrieve the uploaded file as a stream
The HttpPostedFile class also supports the following method:
SaveAs—Enables you to save the uploaded file to the file system
Some redundancy exists here For example, you can get the name of the uploaded file by
using either the FileUpload.FileName property or the HttpPostedFile.FileName property
You can save a file by using either the FileUpload.SaveAs() method or the
HttpPostedFile.SaveAs() method
Trang 8Accepting File Uploads
NOTE
Adding a FileUpload control to a page automatically adds a
enctype=”multipart/form-data” attribute to the server-side <form> tag
Saving Files to the File System
The page in Listing 4.1 illustrates how you can upload images to an application by using
the FileUpload control
LISTING 4.1 FileUploadFile.aspx
<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.IO” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
protected void btnAdd_Click(object sender, EventArgs e)
{
if (upImage.HasFile)
{
if (CheckFileType(upImage.FileName))
{
String filePath = “~/UploadImages/” + upImage.FileName;
upImage.SaveAs(MapPath(filePath));
}
}
}
bool CheckFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case “.gif”:
return true;
case “.png”:
return true;
case “.jpg”:
return true;
Trang 9CHAPTER 4 Using the Rich Controls
case “.jpeg”:
return true;
default:
return false;
}
}
void Page_PreRender()
{
string upFolder = MapPath(“~/UploadImages/”);
DirectoryInfo dir = new DirectoryInfo(upFolder);
dlstImages.DataSource = dir.GetFiles();
dlstImages.DataBind();
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>FileUpload File</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblImageFile”
Text=”Image File:”
AssociatedControlID=”upImage”
Runat=”server” />
<asp:FileUpload
id=”upImage”
Runat=”server” />
<br /><br />
<asp:Button
id=”btnAdd”
Text=”Add Image”
OnClick=”btnAdd_Click”
Runat=”server” />
<hr />
<asp:DataList
Trang 10Accepting File Uploads
id=”dlstImages”
RepeatColumns=”3”
runat=”server”>
<ItemTemplate>
<asp:Image ID=”Image1”
ImageUrl=’<%# Eval(“Name”, “~/UploadImages/{0}”) %>’
style=”width:200px”
Runat=”server” />
<br />
<%# Eval(“Name”) %>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
Listing 4.1 includes both a FileUpload control and a DataList control When you upload
a file, the file is saved to a folder named UploadImages The DataList control
automati-cally displays the contents of the UploadImages folder The result is an image gallery (see
Figure 4.1)