asp.net

391
ASP.Net Full Tutorial (ASP.Net Web Pages,ASP.Net MVC,ASP.Net Web Forms) Created by www.ebooktutorials.blogspot.in Content Downloaded from www.w3schools.com

Upload: ebooktutorials

Post on 27-Oct-2014

11 views

Category:

Documents


4 download

DESCRIPTION

For more tutorials visithttp://ebooktutorials.blogspot.in/

TRANSCRIPT

Page 1: ASP.Net

ASP.Net Full Tutorial (ASP.Net Web Pages,ASP.Net MVC,ASP.Net Web Forms)

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 2: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET

Classic ASP - Active Server PagesActive Server Pages (ASP), also known as Classic ASP, was introduced in 1998 as Microsoft's first server side scripting engine.

ASP is a technology that enables scripts in web pages to be executed by an Internet server.

ASP pages have the file extension .asp, and are normally written in VBScript.

If you want to learn Classic ASP, visit our Classic ASP Tutorial.

ASP.NETASP.NET is a new ASP generation. It is not compatible with Classic ASP, but ASP.NET may include Classic ASP.

ASP.NET pages are compiled, which makes them faster than Classic ASP.

ASP.NET has better language support, a large set of user controls, XML-based components, and integrated user authentication.

ASP.NET pages have the extension .aspx, and are normally written in VB (Visual Basic) or C# (C sharp).

User controls in ASP.NET can be written in different languages, including C++ and Java.

When a browser requests an ASP.NET file, the ASP.NET engine reads the file, compiles and executes the scripts in the file, and returns the result to thebrowser as plain HTML.

ASP.NET RazorRazor is a new and simple markup syntax for embedding server code into ASP.NET web pages, much like Classic ASP.

Razor has the power of traditional ASP.NET, but is easier to use and easier to learn.

ASP.NET Programming LanguagesThis tutorial covers the following programming languages:

Visual Basic (VB.NET)C# (Pronounced C sharp)

ASP.NET Server TechnologiesThis tutorial covers the following server technologies:

Web Pages (with Razor syntax)MVC (Model View Controller)Web Forms (traditional ASP.NET)

ASP.NET Development ToolsASP.NET supports the following development tools:

WebMatrixVisual Web DeveloperVisual Studio

This tutorial uses WebMatrix for Web Pages, and Visual Web Developer for MVC and Web Forms.

ASP.NET File ExtensionsClassic ASP files have the file extension .aspASP.NET files have the file extension .aspxASP.NET files with Razor C# syntax have the file extension .cshtmlASP.NET files with Razor VB syntax have the file extension .vbhtml

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 3: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Demonstration

This is a Web Pages DemonstrationWeb Pages is one of the 3 programming models for creating ASP.NET web sites and web applications.

The other two programming models are Web Forms and MVC (Model, View, Controller).

This demonstration will teach you ASP.NET Web Pages by building a web site:

Create a web siteAdd files and foldersAdd a consistent lookAdd navigationAdd a databaseAdd login and security

Like to Read a Tutorial First?Many developers like to start learning a new technology by looking at a demonstration, but if you want to read the Web Pages tutorial first, go to theASP.NET Web Pages Tutorial.

Easy Learning with "Run Example"Our "Run Example" tool makes it easy to learn Web Pages.

It runs examples and displays the ASP.NET code and the HTML output simultaneously.

Click on the "Run Example" button to see how it works:

Web Pages Example

<html><body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p></body></html>

Run Example »

We Will Use WebMatrixWebMatrix is a simple but powerful free ASP.NET development tool from Microsoft.

WebMatrix is tailor made for Web Pages.

WebMatrix contains:

Web Pages examples and templatesA web server language (Razor using VB or C#)A web server (IIS Express)A database server (SQL Server Compact)A web server markup language (Razor)A full web development framework (ASP.NET)

If you install WebMatrix, you will get the full benefits from this tutorial.

With WebMatrix you can start from scratch with an empty web site and a blank page, or build on open source applications from a "Web Application Gallery".Both PHP and ASP.NET applications are available, such as Umbraco, DotNetNuke, Drupal, Joomla, WordPress and many more. WebMatrix also has built-intools for security, search engine optimization, and web publishing.

The skills and code you develop with WebMatrix can seamlessly be transformed to fully professional ASP.NET applications.

How to Install WebMatrixFollow the link below to install WebMatrix:

http://www.microsoft.com/web/gallery/install.aspx?appid=WebMatrix

Microsoft's Web Platform Installer will install the free components of the Microsoft Web Platform, including WebMatrix, Internet Information Services (IIS),SQL Server Express, and the ASP.NET Framework:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 4: ASP.Net

« Previous Next Chapter »

The Web Platform Installer also makes it easy to install popular free web applications for blogging, content management and more with a built-in WindowsWeb Application Gallery.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 5: ASP.Net

W3Schools.com

« Previous Next Chapter »

ASP.NET Web Pages - WebMatrix

Learn ASP.NET Web Pages by building a web site from scratch.

Part I: Creating a Web Site with WebMatrix.

Create a Web Site with WebMatrixStart WebMatrix, and click Site From Template:

Select Empty Site, name the new site Demo, and click OK:

WebMatrix creates a new site and displays a workspace window with a menu at the top (to publish, run, start, or stop your web site):

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 6: ASP.Net

In the left pane there is a list of your web folders and workspace selector to select working with the site, files, databases, or reports.

Select the Files workspace. This workspace lets you work with files and folders.

Create a Web Page with WebMatrixIn the ribbon bar, click New:

Choose file type CSHTML, (You will learn more about CSHTML files later) and in the Name box, type default.cshtml:

When you click OK, WebMatrix creates a web page and opens it in the editor:

<!DOCTYPE html>

<html lang="en"><head> <meta charset="utf-8" /> <title></title></head><body>

</body></html>

Use the editor to add a title and a heading:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 7: ASP.Net

« Previous Next Chapter »

<!DOCTYPE html>

<html lang="en"><head> <meta charset="utf-8" /> <title>Web Pages Demo</title></head><body> <h1>Hello Web Pages</h1> </body></html>

In the Quick Access Toolbar, click Save:

In the ribbon bar, click Run:

WebMatrix starts a web server (IIS Express) and runs the page on your computer. The page is displayed in your default browser:

Hello Web Pages

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 8: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Files and Folders

Learn ASP.NET Web Pages by building a web site from scratch.

Part II: Creating standard folders and a consistent style.

What We Will DoIn this chapter we will:

Create a new empty web siteCreate the necessary foldersCreate a standard style sheet for the siteCreate a standard layout for the siteCreate a home page for the site

1. Start With an Empty Web SiteIf you have followed this tutorial, you already have a web site called Demo.

If not you can create an empty web site with WebMatrix:

Start WebMatrixClick on "Create Site From Template"Choose "Empty Site"Name the site "Demo"

2. Create FoldersIn the folder named "Demo" (your website), create 5 folders:

Account - for storing login and membership filesApp_Data - for storing databases and data filesImages - for storing imagesScripts - for storing browser scriptsShared - for storing shared style and layout files

3. Create a Style SheetIn the "Shared" folder, create a new style sheet (CSS file) named "Site.css".

Put the following code inside the CSS file:

Site.css

h1{border-bottom: 3px solid #cc9900;font: Georgia, serif;color: #996600;}body{font: "Trebuchet MS", Verdana, sans-serif;background-color: #5c87b2;color: #696969;}#main{padding: 30px;background-color: #ffffff;border-radius: 0 4px 4px 4px;}

The CSS file above defines the styles to be used used for

The HTML heading element <h1>The HTML body element <body>The HTML element with id="main"

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 9: ASP.Net

« Previous Next Chapter »

4. Create a Layout PageIn the "Shared" folder, create a new file named "Layout.cshtml".

Put the following code inside the layout file:

Layout.cshtml

<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="/Shared/Site.css" /></head><body>

<div id="main">@RenderBody()<p>&copy; 2012 W3Schools. All rights reserved.</p></div>

</body></html>

The layout file above defines the layout of your web pages. It has a link to your style sheet file(Shared/Site.css), and a call to the @RenderBody() function, where page content should be displayed.

5. Create a Home PageIn your empty "Demo" folder, create a new file, named "Default.cshtml".

If you created a file with this name earlier, you can edit the existing file, or create a new file with anew name (like Default2.cshtml).

Put the following code inside the file:

Default.cshtml

@{Layout="/Shared/Layout.cshtml";}

<h1>Welcome to W3Schools</h1>

<h2>Web Site Main Ingredients</h2>

<p>A Home Page (Default.cshtml)</p><p>A Layout File (Layout.cshtml)</p><p>A Style Sheet (Site.css)</p>

Run example »

The file starts with a reference to the layout file, otherwise it contains normal HTML markup.

CongratulationsYou have created your first web site, with a main page (the Default page), a common template for allyour pages (the Layout page), and a common style sheet (the CSS file).

In the next chapters of this tutorial, we will add navigation to the web site. Then we will add adatabase, and finally we will add login and security.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 10: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Adding Navigation

Learn ASP.NET Web Pages by building a web site from scratch.

Part III: Adding Navigation.

What We Will DoIn this chapter we will:

Add a PageStart pageAdd an about pageAdd a navigation menu

Add the File: _PageStart.cshtmlIn the root folder (the "Demo" folder), create a new file named "_PageStart.cshtml".

Put the following code inside the file:

_PageStart.cshtml

@{// Set the layout page for the whole siteLayout = "~/Shared/Layout.cshtml";}

The _PageStart file above contains code to be run in every page of the web site. After adding this, youno longer need to add the layout information to every web page.

Add an About PageIn the "Demo" folder, create a new file named "About.cshtml".

Put the following code inside the about file:

About.cshtml

<h1>About Us</h1>

<p> Lorem Ipsum Porem Lorem Ipsum Porem </p>

The about file above contains a heading and a paragraph. Please feel free to edit the content.

Add a Navigation MenuIn the "Shared" folder, edit the layout file.

Put the following code inside the layout file:

Layout.cshtml

<!DOCTYPE html><html> <head> <link rel="stylesheet" type="text/css" href="/Shared/Site.css" /></head><body>

<ul id="menu"><li><a href="/Default">Home</a></li> <li><a href="/About">About</a></li> </ul>

<div id="main"> @RenderBody() <p>&copy; 2012 W3Schools. All rights reserved.</p> </div>

</body> </html>

The layout file above, is a copy of the layout file from the previous chapter, with an added unorderedlist (marked red).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 11: ASP.Net

« Previous Next Chapter »

Edit The Style SheetIn the "Shared" folder, edit your your style sheet (Site.css):

Put the following code inside the file:

Site.css

h1{border-bottom: 3px solid #cc9900;font: Georgia, serif;color: #996600;}body{font: "Trebuchet MS", Verdana, sans-serif;background-color: #5c87b2;color: #696969;}#main{padding: 30px;background-color: #ffffff;border-radius: 0 4px 4px 4px;}

ul#menu{padding: 0px;position: relative;margin: 0;}

ul#menu li{display: inline;}

ul#menu li a {background-color: #e8eef4;padding: 10px 20px;text-decoration: none;line-height: 2.8em;color: #034af3;/*CSS3 properties*/border-radius: 4px 4px 0 0;}

ul#menu li a:hover{background-color: #ffffff;}

The style sheet above, is a copy of the style sheet from the previous chapter, with added styles for anunordered list (marked red).

Edit the Home PageIn your "Demo" folder, edit the file named "Default.cshtml".

Put the following code inside the file:

Default.cshtml

<h1>Welcome to Us</h1>

<p>Lorem Ipsum Porem Lorem Ipsum Porem </p>

Run example »

Feel free to edit the content.

CongratulationsYou have added navigation to your website.

In the next chapter we will add a database.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 12: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Databases

Learn ASP.NET Web Pages by building a web site from scratch.

Part IV: Adding a Database.

What We Will DoIn this chapter we will:

Create a databaseAdd data to the databaseCreate a page to list the database

Displaying Data from DatabaseWith Web Pages, you can easily display data from a database:

Database Example

@{var db = Database.Open("SmallBakery"); var selectQueryString = "SELECT * FROM Product ORDER BY Name"; }<html> <body> <h1>Small Bakery Products</h1> <table> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@foreach(var row in db.Query(selectQueryString)){<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td aligh="right">@row.Price</td> </tr> }</table> </body> </html>

Run example »

Creating a DatabaseWebMatrix includes an SQL Database design tool.

Follow the instructions below to create an SQL database called "SmallBakery".

Open the Databases workspace and click New Database or Add a database.

WebMatrix will create a database with the same name as your site: "Demo.sdf":

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 13: ASP.Net

Rename the database to "SmallBakery.sdf".

Click New Table.

Click New Column and create 4 columns named "Id", "Name", "Description", and "Price".

For all columns, set Allows Null to "False".

For the "Id" column, Set Data Type to "bigint", Is Identity to "True", and Is Primary Key to "True".

For the "Name" and "Description" columns, set Data Type to "nvarchar".

For the "Price" column, set Data Type to "money".

Save the table and name it "Product".

When you are finished, your table design will look like this:

Notes:

Allow Nulls = "False" specifies that the column cannot be blank (empty).

Is Primary Key tells the database that this will be the table's primary key.

Is Identity tells the database to assign a new ID number for every record (starting at 1).

Data Type = "nvarchar" specifies that this column is a string of variable length.(The n prefix indicates that the column can hold international Unicode characters)

Adding Data to the DatabaseFollow the instructions below to add some data to your database:

In the left pane, expand the SmallBakery.sdf node and then click Tables.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 14: ASP.Net

« Previous Next Chapter »

Right-click the Product table and then click Data.

In the edit pane, enter the following records:

Name Description Price

Bread Baked fresh every day 2.99

Strawberry Cake Made with organic strawberries 9.99

Apple Pie Second only to your mom's pie 12.99

Pecan Pie If you like pecans, this is for you 10.99

Lemon Pie Made with the best lemons in the world 11.99

Cupcakes Your kids will love these 7.99

Creating a Test PageFollow the instructions below to create a test page for your database:

In the root folder (the Demo folder), create a new web page named ListProducts.cshtml.

Replace the code in the file with the code from the example above:

ListProducts.cshtml

@{var db = Database.Open("SmallBakery"); var selectQueryString = "SELECT * FROM Product ORDER BY Name"; }<html> <body> <h1>Small Bakery Products</h1> <table> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@foreach(var row in db.Query(selectQueryString)){<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td aligh="right">@row.Price</td> </tr> }</table> </body> </html>

Add the Test Page to Your ApplicationAdd a new line to your layout file:

Layout.cshtml

<ul id="menu"><li><a href="/Default">Home</a></li><li><a href="/ListProducts">Data</a></li><li><a href="/About">About</a></li></ul>

Run example »

Database ConnectionThe Database.Open(name) method will connect to a database in two steps:

First, it searches the application's App_Data folder for a database that matches the name parameter without the file-name extension.

If no file is found, it looks for a connection string in the application's Web.config file.

This two-step search makes it possible to test the application with a local database, and run the application on a web host using a connection string.

A connection string contains information about how to connect to a database. It can include a file path, or the name of an SQL database, with full username and password.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 15: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Adding Registration and Login

Learn ASP.NET Web Pages by building a web site from scratch.

Part V: Adding Membership registration, and Login.

What We Will DoIn this chapter we will:

Create a WebSecurity database to hold user profiles and membership informationInitialize WebSecurity in AppStartAdd a membership registration pageAdd a member login page

The WebSecurity ObjectThe WebSecurity Object provides security and authentication for ASP.NET Web Pages applications.

With the WebSecurity object you can create user accounts, login and logout users, reset or changepasswords, and more.

Create a WebSecurity DatabaseWe will create a new WebSecurity database to store user profiles, logins, passwords, and membershipinformation.

You don't have to create a new database. You can use your existing database(SmallBakery.sdf).

Select the Databases workspace in WebMatrix, and click "Add a database to your site" to create anew SQL Server Compact database.

Name the database "Users.sdf"

The database will be created in the App_Data folder of your web.

Create an AppStart PageIn the root of your web (the demo folder), create a new page named _AppStart.cshtml.

Put the following code inside the file:

_AppStart.cshtml

@{WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId","Email", true);}

The code above will be run each time your web site (application) starts. It initializes the WebSecuritydatabase (Users.sdf), with user profile tables, if it is not already initialized.

"Users" is the name of the database.

"UserProfile" is the name of the database table that contains the user profile information.

"UserId" is the name of the (integer) column that contains the user IDs.

"Email" is the name of the (string) column that contains user names.

true is a boolean value indicating that the user profile and membership tables should be createdautomatically if they don't exist. Otherwise set to false.

Although true indicates that the membership tables can be created automatically, thedatabase itself must always exist.

Edit The Style SheetIn the "Shared" folder, edit your your style sheet (Site.css):

Add the following CSS code to the file:

Site.css

/* Forms --------------------*/ fieldset label{display:block;padding:4px;

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 16: ASP.Net

}

input[type="text"],input[type="password"]{width:300px;}

input[type="submit"]{padding:4px;}

Add a Registration PageIn the "Account" folder, create a new file named "Register.cshtml".

Put the following code inside the file:

Register.cshtml

@{// Initialize pagevar email = "";var password = "";var confirmPassword = "";var ErrorMessage = "";

// If this is a POST request, validate and process dataif (IsPost){email = Request.Form["email"];password = Request.Form["password"];confirmPassword = Request.Form["confirmPassword"];

if (email.IsEmpty() || password.IsEmpty()) {ErrorMessage = "You must specify both email and password.";}

if (password != confirmPassword) {ErrorMessage = "Password and confirmation do not match.";}

// If all information is valid, create a new accountif (ErrorMessage==""){ var db = Database.Open("Users");var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email)= LOWER(@0)", email);if (user == null){db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);WebSecurity.CreateAccount(email, password, false);

// Navigate back to the homepage and exitResponse.Redirect("~/");} else {ErrorMessage = "Email address is already in use.";}}}}

@if (ErrorMessage!=""){<p>@ErrorMessage</p> <p>Please correct the errors and try again.</p>}

<form method="post" action=""><fieldset><legend>Sign-up Form</legend><ol><li><label>Email:</label><input type="text" id="email" name="email"</li><li><label>Password:</label><input type="password" id="password" name="password"</li><li><label>Confirm Password:</label><input type="password" id="confirmPassword" name="confirmPassword" </li><li><p><input type="submit" value="Register" /></p></li></ol></fieldset></form>

Add a Login PageIn the "Account" folder, create a new file named "Login.cshtml".

Put the following code inside the file:

Login.cshtml

@{// Initialize pagevar username = "";

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 17: ASP.Net

« Previous Next Chapter »

var password = "";var ErrorMessage = "";

// If this is a POST request, validate and process dataif (IsPost){username = Request.Form["username"];password = Request.Form["password"];if (username.IsEmpty() || password.IsEmpty()){ErrorMessage = "You must specify a username and password.";} else{// Login, Navigate back to the homepage and exitif (WebSecurity.Login(username, password, false)){Response.Redirect("~/");}else{ErrorMessage = "Login failed";}}}}

@if (ErrorMessage!="") {<p>@ErrorMessage</p> <p>Please correct the errors and try again.</p>}

<form method="post" action=""><fieldset><legend>Log In to Your Account</legend><ol><li><label>Username:</label><input type="text" id="username" name="username" /></li><li><label>Password:</label><input type="password" id="password" name="password" /></li><li><p><input type="submit" value="login" /></p></li></ol></fieldset></form>

Edit the Navigation MenuIn the "Shared" folder, edit the layout file.

Put the following code inside the layout file:

Layout.cshtml

<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="/Shared/Site.css" /></head><body><ul id="menu"><li><a href="/Default.cshtml">Home</a></li><li><a href="/ListProducts">Data</a></li><li><a href="/About">About</a></li><li><a href="/Account/Register">Register</a></li><li><a href="/Account/Login">Login</a></li></ul>

<div id="main">@RenderBody()<p>&copy; 2012 W3Schools. All rights reserved.</p></div>

</body></html>

The layout file above, is a copy of the layout file from the previous chapter, with the Register an Loginpages added to the navigation menu (marked red).

CongratulationsYou have added membership registration and login information to your website.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 18: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Security

Learn ASP.NET Web Pages by building a web site from scratch.

Part VI: Security.

What We Will DoIn this chapter we will:

Add access restriction security to a web page

Membership, Login, and SecurityIn the previous chapter we added a registration page and a login page to the web site.

When a membership is registered, the user can login, with his email address and password.

However, user membership and login functions do not automatically restrict (or open) any access to the web site.

Security (access restrictions) has to be added to each of the web pages.

Adding Security to PagesAccess restrictions (security) can easily be added to any web page.

Just put the following code inside the page:

Security Code:

if (!WebSecurity.IsAuthenticated){Response.Redirect("~/Account/Login");}

The code above executes an if test, asking if the user is logged in. If not, the user is redirected to the login page.

Preventing Access to the DatabaseIn our example, the page ListProducts.cshtml, lists bakery products from the "SmallBakery" database.

Add the security code at the beginning of the page:

ListProducts.cshtml

@{if (!WebSecurity.IsAuthenticated){Response.Redirect("~/Account/Login");}var db = Database.Open("SmallBakery"); var selectQueryString = "SELECT * FROM Product ORDER BY Name"; }<html> <body> <h1>Small Bakery Products</h1> <table> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@foreach(var row in db.Query(selectQueryString)){<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td aligh="right">@row.Price</td> </tr> }</table> </body> </html>

The ListProducts page above, is a copy of the page from the previous chapter about databases. The security code is (added at the beginning) is markedred.

CongratulationsYou have added security to your web site, using the WebSecurity object.

For a full reference to the WebSecurity object, please visit our WebSecurity Object Reference.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 19: ASP.Net

« Previous Next Chapter »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 20: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Tutorial

ASP.NET is a development framework for building web pages andweb sites with HTML, CSS, JavaScript and server scripting.

ASP.NET supports three different development methods:Web Pages, MVC (Model View Controller), and Web Forms.

THIS TUTORIAL COVERS WEB PAGES.

Web Pages MVC Web Forms

ASP.NET Framework

Easy Learning with "Run Example"Our "Run Example" tool makes it easy to learn Web Pages.

It runs examples and displays the ASP.NET code and the HTML output simultaneously.

Click on the "Run Example" button to see how it works:

Web Pages Example

<html><body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p></body></html>

Run Example »

What is Web Pages?Web Pages is one of the 3 programming models for creating ASP.NET web sites and web applications.

The other two programming models are Web Forms and MVC (Model, View, Controller).

Web Pages is the simplest programming model for developing ASP.NET web pages. It provides an easy way to combine HTML, CSS, JavaScript and servercode:

Easy to learn, understand, and useBuilt around single web pagesSimilar to PHP and Classic ASPServer scripting with Visual Basic or C#Full HTML, CSS, and JavaScript control

Web Pages are easy extendable with programmable Web Helpers, including database, video, graphics, social networking and much more.

Where to Start?Many developers like to start learning a new technology by looking at working examples.

If you want to take a look at a working Web Pages examples, follow the ASP.NET Web Pages Demo.

Web Pages TutorialIf you are new to ASP.NET, Web Pages is the perfect place to start.

In our Web Pages tutorial you will learn how to combine HTML, CSS, JavaScript and server code, using the latest Razor server markup syntax with VisualBasic or C# .

You will also learn how to extend your web pages with programmable Web Helpers.

We Will Use WebMatrixWebMatrix is a simple and powerful free development tool from Microsoft.

WebMatrix is tailor made for Web Pages.

Install WebMatrix now!

Web Pages ExamplesLearn by examples!

Because ASP.NET code is executed on the server, you cannot view the code in your browser. You will only see the output as plain HTML.

At W3Schools every example displays the hidden ASP.NET code. This makes it easier for you to understand how it works.

Web Pages Examples

Web Pages ReferencesAt the end of this tutorial you will find a complete set of ASP.NET references with objects, components, properties and methods.

Web Pages References

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 21: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Adding Razor Code

In this tutorial we will use Razor markup with C# and Visual Basic code

What is Razor?Razor is a markup syntax for adding server-based code to web pagesRazor has the power of traditional ASP.NET markup, but is easier to learn, and easier to useRazor is a server side markup syntax much like ASP and PHPRazor supports C# and Visual Basic programming languages

Adding Razor CodeRemember the web page from previous chapter:

<!DOCTYPE html>

<html lang="en"><head> <meta charset="utf-8" /> <title>Web Pages Demo</title></head><body> <h1>Hello Web Pages</h1></body></html>

Now add some Razor code to the example:

Example

<!DOCTYPE html>

<html lang="en"><head> <meta charset="utf-8" /> <title>Web Pages Demo</title></head><body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p></body></html>

Run example »

The page contains ordinary HTML markup, with one addition: the @ marked Razor code.

The Razor code does all the work of determining the current time on the server and display it. (You can specify formatting options, or just display thedefault)

Main Razor Syntax Rules for C#Razor code blocks are enclosed in @{ ... }Inline expressions (variables and functions) start with @Code statements end with semicolonVariables are declared with the var keywordStrings are enclosed with quotation marksC# code is case sensitiveC# files have the extension .cshtml

C# Example

<!-- Single statement block -->@{ var myMessage = "Hello World"; }

<!-- Inline expression or variable --><p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->@{var greeting = "Welcome to our site!";var weekDay = DateTime.Now.DayOfWeek;var greetingMessage = greeting + " Today is: " + weekDay;}<p>The greeting is: @greetingMessage</p>

Run example »

Main Razor Syntax Rules for VBRazor code blocks are enclosed in @Code ... End Code

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 22: ASP.Net

« Previous Next Chapter »

Inline expressions (variables and functions) start with @Variables are declared with the Dim keywordStrings are enclosed with quotation marksVB code is not case sensitiveVB files have the extension .vbhtml

Example

<!-- Single statement block --> @Code dim myMessage = "Hello World" End Code <!-- Inline expression or variable --> <p>The value of myMessage is: @myMessage</p> <!-- Multi-statement block --> @Codedim greeting = "Welcome to our site!" dim weekDay = DateTime.Now.DayOfWeek dim greetingMessage = greeting & " Today is: " & weekDayEnd Code

<p>The greeting is: @greetingMessage</p>

Run example »

More About C# and Visual BasicIf you want to learn more about Razor, and the C# and Visual Basic programming languages, go to the Razor section of this tutorial.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 23: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Page Layout

With Web Pages it is easy to create a web site with a consistent layout.

A Consistent LookOn the Internet you will discover many web sites with a consistent look and feel:

Every page have the same headerEvery page have the same footerEvery page have the same style and layout

With Web Pages this can be done very efficiently. You can have reusable blocks of content (content blocks), like headers and footers, in separate files.

You can also define a consistent layout for all your pages, using a layout template (layout file).

Content BlocksMany websites have content that is displayed on every page (like headers and footers).

With Web Pages you can use the @RenderPage() method to import content from separate files.

Content block (from another file) can be imported anywhere in a web page, and can contain text, markup, and code, just like any regular web page.

Using common headers and footers as an example, this saves you a lot of work. You don't have to write the same content in every page, and when youchange the header or footer files, the content is updated in all your pages.

This is how it looks in code:

Example

<html><body>@RenderPage("header.cshtml")<h1>Hello Web Pages</h1> <p>This is a paragraph</p>@RenderPage("footer.cshtml")</body></html>

Run example »

Using a Layout PageIn the previous section, you saw that including the same content in many web pages is easy.

Another approach to creating a consistent look is to use a layout page. A layout page contains the structure, but not the content, of a web page. When aweb page (content page) is linked to a layout page, it will be displayed according to the layout page (template).

The layout page is just like a normal web page, except from a call to the @RenderBody() method where the content page will be included.

Each content page must start with a Layout directive.

This is how it looks in code:

Layout Page:

<html><body><p>This is header text</p>@RenderBody()<p>&copy; 2012 W3Schools. All rights reserved.</p></body></html>

Any Web Page:

@{Layout="Layout.cshtml";}

<h1>Welcome to W3Schools</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laborisnisi ut aliquip ex ea commodoconsequat.</p>

Run example »

D.R.Y. - Don't Repeat Yourself

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 24: ASP.Net

« Previous Next Chapter »

With two ASP.NET tools, Content Blocks and Layout Pages, you can give your web applications a consistent look.

These tools also save you a lot of work, since you don't have to repeat the same information on all pages. Centralizing markup, style, and code makes webapplications much more manageable and easier to maintain.

Preventing Files from Being BrowsedWith ASP.NET, files with a name that starts with an underscore cannot be browsed from the web.

If you want to prevent your content blocks or layout files from being viewed by your users, rename the files to:

_header.cshtm

_footer.cshtml

_Layout.cshtml

Hiding Sensitive InformationWith ASP.NET, the common way to hide sensitive information (database passwords, email passwords, etc.) is to keep the information in a separate filenamed "_AppStart".

_AppStart.cshtml

@{WebMail.SmtpServer = "mailserver.example.com";WebMail.EnableSsl = true;WebMail.UserName = "[email protected]";WebMail.Password = "your-password";WebMail.From = "[email protected]";}

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 25: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Folders

This chapter is about folders and folder paths.

In this chapter you will learn:

About Logical and Physical folder structuresAbout Virtual and Physical namesAbout web URLs and Paths

Logical Folder StructureBelow is a typical folder structure for an ASP.NET web pages web:

The "Account" folder contains logon and security filesThe "App_Data" folder contains databases and data filesThe "Images" folder contains imagesThe "Scripts" folder contains browser scriptsThe "Shared" folder contains common files (like layout and style files)

Physical Folder StructureThe physical structure for the "Images" folder at the website above might look like this on a computer:

C:\Johnny\Documents\MyWebSites\Demo\Images

Virtual and Physical NamesFrom the example above:

The virtual name of a web picture might be "Images/pic31.jpg".

But the physical name is "C:\Johnny\Documents\MyWebSites\Demo\Images\pic31.jpg"

URLs and PathsURLs are used to access files from the web: http://www.w3schools.com/html5/html5_intro.asp

The URL corresponds to a physical file on a server: C:\MyWebSites\htm5\html5_intro.asp

A virtual path is shorthand to represent physical paths. If you use virtual paths, you can move your pages to a different domain (or server) without havingto update the paths.

URL http://www.w3schools.com/html5/html5_intro.aspServer name w3schoolsVirtual path /html5/html5_intro.aspPhysical path C:\MyWebSites\w3schools\/html5/html5_intro.asp

The root on a disk drive is written like C:\, but the root on a web site is / (forward slash).

The virtual path of a web folder is (almost) never the same as the physical folder.

In your code you will, reference both the physical path and the virtual path, depending on what you are coding.

ASP.NET has 3 tools for working with folder paths: the ~ operator, the Server.MapPath method, and the Href method.

The ~ OperatorTo specify the virtual root in programming code, use the ~ operator.

If you use the ~ operator, instead of a path, you can move your website to a different folder or location without changing any code:

var myImagesFolder = "~/images";var myStyleSheet = "~/styles/StyleSheet.css";

The Server.MapPath MethodThe Server.MapPath method converts a virtual path (/default.cshtml) to a physical path that the server can understand(C:\Johnny\MyWebSited\Demo\default.cshtml).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 26: ASP.Net

« Previous Next Chapter »

You will use this method when you need to open data files located on the server (data files can only be accessed with a full physical path):

var pathName = "~/dataFile.txt";var fileName = Server.MapPath(pathName);

You will learn more about reading from (and writing to) data files on the server in the next chapter of this tutorial.

The Href MethodThe Href method converts a path used in the code to a path that the browser can understand (the browser cannot understand the ~ operator).

You use the Href method to create paths to resources like image files, and CSS files.

You will often use this method in HTML <a>, <img>, and <link> elements:

@{var myStyleSheet = "~/Shared/Site.css";}

<!-- This creates a link to the CSS file. --><link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" />

<!-- Same as : --><link rel="stylesheet" type="text/css" href="/Shared/Site.css" />

The Href method is a method of the WebPage Object.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 27: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Global Pages

This chapter is about the global pages AppStart and PageStart.

Before Web Startup: _AppStartMost server side code are written inside individual web pages. For example, if a web page contains an input form, the web page typically contains servercode for reading the data.

However, by creating a page named _AppStart in the root of your site, you can have startup code executed before the site starts. If this page exists,ASP.NET runs it the first time any page in the site is requested.

Typical use for _AppStart is startup code and initialization of global values like counters and global names.

Note 1: _AppStart should have the same file extension as your web pages, like: _AppStart.cshtml.

Note 2: _AppStart has an underscore prefix. Because of this, the files cannot be browsed directly.

Before Every Page: _PageStartJust like _AppStart runs before your site starts, you can write code that runs before any page in each folder.

For each folder in your web, you can add a file named _PageStart.

Typical use for _PageStart is setting the layout page for all pages in a folder, or checking that a user is logged in before running a page.

How Does it Work?The following diagram shows how it works:

When a request comes in, ASP.NET checks whether _AppStart exists. If so, and this is the first request to the site, _AppStart runs.

Then ASP.NET checks whether _PageStart exists. If so, _PageStart runs, before the requested page.

If you include a call to RunPage() inside _PageStart you specify where you want the requested page to run. If not, the _PageStart runs before the requestedpage.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 28: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - HTML Forms

A form is a section of an HTML document where you put input controls (text boxes, check boxes, radio buttons, and pull-down lists)

Creating an HTML Input Page

Razor Example

<html><body> @{if (IsPost) { string companyname = Request["companyname"]; string contactname = Request["contactname"]; <p>You entered: <br />Company Name: @companyname <br />Contact Name: @contactname </p>}else{<form method="post" action="">Company Name:<br /><input type="text" name="CompanyName" value="" /><br />Contact Name:<br /><input type="text" name="ContactName" value="" /><br /><br /><input type="submit" value="Submit" class="submit" /></form>}} </body> </html>

Run example »

Razor Example - Displaying ImagesSuppose you have 3 images in your image folder, and you want to display images dynamically by the users choice.

This is easily done by a little Razor code.

If you have an image called "Photo1.jpg" in your images folder on your web site, you can display the image using an HTML <img> element like this:

<img src="images/Photo1.jpg" alt="Sample" />

The example below shows how to display a selected picture which the user selects from a drop-down list:

Razor Example

@{var imagePath=""; if (Request["Choice"] != null) {imagePath="images/" + Request["Choice"];} } <!DOCTYPE html> <html> <body> <h1>Display Images</h1> <form method="post" action=""> I want to see: <select name="Choice"> <option value="Photo1.jpg">Photo 1</option> <option value="Photo2.jpg">Photo 2</option> <option value="Photo3.jpg">Photo 3</option> </select> <input type="submit" value="Submit" /> @if (imagePath != ""){<p><img src="@imagePath" alt="Sample" /></p>} </form> </body> </html>

Run example »

Example explainedThe server creates a variable called imagePath.

The HTML page has a drop-down list (a <select> element) named Choice. It lets the user select a friendly name (like Photo 1), and passes a file name(like Photo1.jpg) when the page is submitted to the web server.

The Razor code reads the value of Choice by Request["Choice"]. If it has a value the code constructs a path to the image (images/Photo1.jpg, and storesit in the variable imagePath.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 29: ASP.Net

« Previous Next Chapter »

In the HTML page there is an <img> element to display the image. The src attribute is set to the value of the imagePath variable when the page displays.

The <img> element is in an if block to prevent trying to display an image with no name (like the first time the page is displayed.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 30: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Objects

Web Pages is much often about Objects.

The Page ObjectYou have already seen some Page Object methods in use:

@RenderPage("header.cshtml")

@RenderBody()

In the previous chapter you saw two Page Object properties being used (isPost, and Request):

If (isPost) {

if (Request["Choice"] != null {

Some Page Object Methods

Method Description

href Builds a URL using the specified parameters

RenderBody() Renders the portion of a content page that is not within a named section (In layout pages)

RenderPage(page) Renders the content of one page within another page

RenderSection(section) Renders the content of a named section (In layout pages)

Write(object) Writes the object as an HTML-encoded string

WriteLitteral Writes an object without HTML-encoding it first.

Some Page Object Properties

Property Description

isPost Returns true if the HTTP data transfer method used by the client is a POST request

Layout Gets or sets the path of a layout page

Page Provides property-like access to data shared between pages and layout pages

Request Gets the HttpRequest object for the current HTTP request

Server Gets the HttpServerUtility object that provides web-page processing methods

The Page Property (of the Page Object)The Page property of the Page Object, provides property-like access to data shared between pages and layout pages.

You can use (add) your own properties to the Page property:

Page.TitlePage.VersionPage.anythingyoulike

The pages property is very helpful. For instance, it makes it possible to set the page title in content files, and use it in the layout file:

Home.cshtml

@{Layout="~/Shared/Layout.cshtml";Page.Title="Home Page"}

<h1>Welcome to W3Schools</h1>

<h2>Web Site Main Ingredients</h2>

<p>A Home Page (Default.cshtml)</p><p>A Layout File (Layout.cshtml)</p><p>A Style Sheet (Site.css)</p>

Layout.cshtml

<!DOCTYPE html><html><head><title>@Page.Title</title></head><body>@RenderBody()</body>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 31: ASP.Net

« Previous Next Chapter »

</html

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 32: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Files

This chapter is about working with text files.

Working with Text FilesIn a previous chapter, we looked at web data stored in a database.

Your web site may also have data stored in text files.

Text files used to store data is often called flat files. Common text file formats are .txt, .xml, and .csv (comma-delimited values).

In this chapter you will learn:

How to read and display data from a text file

Add a Text File ManuallyIn the example to follow, you will need a text file to work with.

On your web site, if you don't have an App_Data folder, create one. In the App_Data folder, create a new file named Persons.txt.

Add the following content to the file:

Persons.txt

George,LucasSteven,SpielbergAlfred,Hitchcock

Displaying Data from a Text FileThe example below shows how to display data from a text file:

Example

@{var dataFile = Server.MapPath("~/App_Data/Persons.txt");Array userData = File.ReadAllLines(dataFile);}

<!DOCTYPE html><html><body>

<h1>Reading Data from a File</h1>@foreach (string dataLine in userData) { foreach (string dataItem in dataLine.Split(',')) {@dataItem <text>&nbsp;</text>} <br />}</body></html>

Run example »

Example explainedServer.MapPath finds the exact text file path.

File.ReadAllLines opens the text file and reads all lines from the file into an array.

For each dataItem in each dataline of the array the data is displayed.

Displaying Data from an Excel FileWith Microsoft Excel, you can save a spreadsheet as a comma-delimited text file (.csv file). When you do so, each row in the spreadsheet is saved as a textline, and each data column is separated by a comma.

You can use the example above to read an Excel .csv file (just change the file name to the name of the Excel file).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 33: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Helpers

Web Helpers greatly simplifies web development and common programming tasks.

ASP.NET HelpersASP.NET helpers are components that can be accessed by single lines of Razor code.

You can build your own helpers using Razor syntax stored as .cshtml files, or use built-in ASP.NET helpers.

You will learn how to use Razor helpers in the next chapters of this tutorial.

Below is a short description of some useful Razor helpers:

The WebGrid HelperThe WebGrid helper simplifies the way to display data:

Automatically sets up an HTML table to display dataSupports different options for formattingSupports paging (First, next, previous, last) through dataSupports sorting by clicking on column headings

The Chart HelperThe "Chart Helper" can display chart images of different types with many formatting options and labels.

The Chart helper can display data from arrays , from databases, or from files.

The WebMail HelperThe WebMail helper provides functions for sending email messages using SMTP (Simple Mail Transfer Protocol).

The WebImage HelperThe WebImage helper provides functionality to manage images in a web page.

Keywords: flip, rotate, resize, watermark.

Third Party HelpersWith Razor you can take advantage of built-in or third party helpers to simplify the use of email, databases, multimedia, and social networks as well asmany other issues like navigation and web security.

Installing HelpersSome helpers are already included with WebMatrix, but you can install others as well.

In the W3Schools Helper Reference you can find a quick reference for included helpers and other helpers that you can install as part of a package called theASP.NET Web Helpers Library.

If you have a web site created in WebMatrix, use the following procedure to install helpers:

1. In WebMatrix, open the Site workspace.2. Click on Web Pages Administration.3. Login to Web Pages Administration using a password *.4. Search for helpers using the search field.5. Click install to install your desired helpers.

(* the first time you use Web Pages Administration, it will prompt you to create a password)

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 34: ASP.Net

« Previous Next Chapter »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 35: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - The WebGrid Helper

WebGrid - One of many useful ASP.NET Web Helpers.

Doing the HTML YourselfIn the previous chapter, you displayed database data by using razor code, and doing all the HTML markup yourself:

Database Example

@{var db = Database.Open("SmallBakery"); var selectQueryString = "SELECT * FROM Product ORDER BY Name"; }<html> <body> <h1>Small Bakery Products</h1> <table> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@foreach(var row in db.Query(selectQueryString)){<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td align="right">@row.Price</td> </tr> }</table> </body> </html>

Run example »

Using The WebGrid HelperUsing the WebGrid helper is an easier way to display data.

The WebGrid helper:

Automatically sets up an HTML table to display dataSupports different options for formattingSupports paging through dataSupports Sorting by clicking on column headings

WebGrid Example

@{ var db = Database.Open("SmallBakery") ; var selectQueryString = "SELECT * FROM Product ORDER BY Id"; var data = db.Query(selectQueryString); var grid = new WebGrid(data); }<html> <head> <title>Displaying Data Using the WebGrid Helper</title> </head> <body> <h1>Small Bakery Products</h1> <div id="grid"> @grid.GetHtml()</div> </body> </html>

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 36: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - The Chart Helper

The Chart Helper - One of many useful ASP.NET Web Helpers.

The Chart HelperIn the previous chapters, you learned how to use an ASP.NET "Helper".

You learned how to display data in a grid using the "WebGrid Helper".

This chapter explains how to display data in graphical form, using the "Chart Helper".

The "Chart Helper" can create chart images of different types with many formatting options and labels.It can create standard charts like area charts, bar charts, column charts, line charts, and pie charts,along with more specialized charts like stock charts.

The data you display in a chart can be from an array, from a database, or from data in a file.

Chart From an ArrayThe example below shows the code needed to display a chart from an array of values:

Example

@{ var myChart = new Chart(width: 600, height: 400) .AddTitle("Employees") .AddSeries(chartType: "column", xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" }, yValues: new[] { "2", "6", "4", "5", "3" }) .Write();}

Run example »

- new Chart creates a new chart object and sets its width and height

- the AddTitle method specifies the chart title

- the AddSeries method adds data to the chart

- the chartType parameter defines the type of chart

- the xValue parameter defines x-axis names

- the yValues parameter defines the y-axis values

- the Write() method displays the chart

Chart From Database DataYou can run a database query and then use data from the results to create a chart:

Example

@{ var db = Database.Open("SmallBakery"); var dbdata = db.Query("SELECT Name, Price FROM Product"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Product Sales") .DataBindTable(dataSource: dbdata, xField: "Name") .Write();}

Run example »

- var db = Database.Open opens the database (and assigns the database object to the variable db)

- var dbdata = db.Query runs a database query and stores the result in dbdata

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 37: ASP.Net

« Previous Next Chapter »

- new Chart creates a chart new object and sets its width and height

- the AddTitle method specifies the chart title

- the DataBindTable method binds the data source to the chart

- the Write() method displays the chart

An alternative to using the DataBindTable method is to use AddSeries (See previous example).DataBindTable is easier to use, but AddSeries is more flexible because you can specify the chart anddata more explicitly:

Example

@{ var db = Database.Open("SmallBakery"); var dbdata = db.Query("SELECT Name, Price FROM Product"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Product Sales") .AddSeries(chartType:"Pie", xValue: dbdata, xField: "Name", yValues: dbdata, yFields: "Price") .Write();}

Run example »

Chart From XML Data

The third option for charting is to use an XML file as the data for the chart:

Example

@using System.Data;

@{var dataSet = new DataSet();dataSet.ReadXmlSchema(Server.MapPath("data.xsd"));dataSet.ReadXml(Server.MapPath("data.xml"));var dataView = new DataView(dataSet.Tables[0]);var myChart = new Chart(width: 600, height: 400) .AddTitle("Sales Per Employee") .AddSeries("Default", chartType: "Pie", xValue: dataView, xField: "Name", yValues: dataView, yFields: "Sales") .Write();}}

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 38: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - The WebMail Helper

The WebMail Helper - One of many useful ASP.NET Web Helpers.

The WebMail HelperThe WebMail Helper makes it easy to send an email from a web application using SMTP (Simple Mail transfer Protocol).

Scenario: Email SupportTo demonstrate the use of email, we will create an input page for support, let the user submit the page to another page, and send an email about thesupport problem.

First: Edit Your AppStart PageIf you have built the Demo application in this tutorial, you already have a page called _AppStart.cshtml with the following content:

_AppStart.cshtml

@{WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId","Email", true);}

To initiate the WebMail helper, add the the following WebMail properties to your AppStart page:

_AppStart.cshtml

@{WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId","Email", true);WebMail.SmtpServer = "smtp.example.com";WebMail.SmtpPort = 25;WebMail.EnableSsl = false;WebMail.UserName = "[email protected]";WebMail.Password = "password-goes-here";WebMail.From = "[email protected]";}

Properties explained:

SmtpServer: The name the SMTP server that will be used to send the emails.

SmtpPort: The port the server will use to send SMTP transactions (emails).

EnableSsl: True, if the server should use SSL (Secure Socket Layer) encryption.

UserName: The name of the SMTP email account used to send the email.

Password: The password of the SMTP email account.

From: The email to appear in the from address (often the same as UserName).

Second: Create an Email Input PageThen create an input page, and name it Email_Input:

Email_Input.cshtml

<!DOCTYPE html> <html> <body> <h1>Request for Assistance</h1>

<form method="post" action="EmailSend.cshtml"> <label>Username:</label><input type="text name="customerEmail" /><label>Details about the problem:</label> <textarea name="customerRequest" cols="45" rows="4"></textarea> <p><input type="submit" value="Submit" /></p> </form>

</body> </html>}

The purpose of the input page is to collect information, then submit the data to a new page that can send the information as an email.

Third: Create An Email Send Page

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 39: ASP.Net

« Previous Next Chapter »

Then create the page that will be used to send the email, and name it Email_Send:

Email_Send.cshtml

@{ // Read inputvar customerEmail = Request["customerEmail"];var customerRequest = Request["customerRequest"];try{// Send email WebMail.Send(to:"[email protected]", subject: "Help request from - " +customerEmail, body: customerRequest ); }catch (Exception ex ){<text>@ex</text> }}

For more information about sending emails from a ASP.NET Web Pages application, please see the: WebMail Object Reference.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 40: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - PHP

Attention PHP Developers. Web Pages can be written in PHP.

WebMatrix Supports PHPAt first look, WebMatrix only supports Microsoft technologies. This is not true. In WebMatrix you can write full PHP applications with MySQL and all.

Create a PHP SiteIn the chapter ASP.NET Web Pages - Create a Web Site you created a new empty web site named "Demo", with a new empty page of the type "CSHTML".

Repeat the process, create an empty site named "Demo_PHP", enable PHP (see picture below), create a new empty page of the type PHP, name it"index.php", and you have created your first PHP site.

Create a PHP PagePut the following code inside the "index.php" file:

index.php

<!DOCTYPE html><html><body>

<?phpphpinfo();?>

</body></html>

Run the file and see PHP at work.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 41: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - Publishing the Website

Learn how to publish a Web Pages application without using WebMatrix.

Publish Your Application Without Using WebMatrixAn ASP.NET Web Pages application can be published to a remote server by using the Publish commands in WebMatrix (,Visual Web Developer,or VisualStudio).

This function copies all your application files, cshtml pages, images, and all the required DLL files for Web Pages, for Razor, for Helpers, and for SQL ServerCompact (if a database is used).

Sometimes you don't want to use this option. Maybe your hosting provider only supports FTP? Maybe you already have a web site based on classic ASP?Maybe you want to copy the files yourself? Maybe you want to use Front Page, Expression Web, or some other publishing software?

Will you get a problem? Yes, you will. But you can solve it.

To perform a web copy, you have to know how to include the right files, what DDL files to copy, and where store them.

Follow these steps:

1. Use the Latest Version of ASP.NETBefore you continue, make sure your hosting computer runs the latest version of ASP.NET (4.0).

2. Copy the Web FoldersCopy your website (all folders and content) from your development computer to an application folder on your remote hosting computer (server).

If your App_Data folder contains test data, don't copy the App_Data folder (see SQL Data below).

3. Copy the DLL FilesOn the remote server create a bin folder in the root of your application. (If you have installed Helpers, you already have a bin folder)

Copy everything from your folder:

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies

to your application's bin folder on the remote server.

4. Copy the SQL Server Compact DLL FilesIf your application has a SQL Server Compact database (an .sdf file in App_Data folder), you must copy the SQL Server Compact DLL files:

Copy everything from your folder:

C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Private

to your application's bin folder on the remote server.

Create (or edit) the Web.config file for your application:

Example C#

<?xml version="1.0" encoding="UTF-8"?><configuration><system.data><DbProviderFactories><remove invariant="System.Data.SqlServerCe.4.0" />

<add invariant="System.Data.SqlServerCe.4.0"name="Microsoft SQL Server Compact 4.0"description=".NET Framework Data Provider for Microsoft SQL Server Compact"type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe,Version=4.0.0.1,Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

</DbProviderFactories></system.data></configuration>

5. Copy SQL Server Compact DataDo you have .sdf files in your App_Data folder that contains test data?

Do you want to publish the test data to the remote server?

Most likely not.

If you have to copy the SQL data files (.sdf files), you should delete everything in the database, and then copy the empty .sdf file from your developmentcomputer to the server.

THAT'S IT. GOOD LUCK !

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 42: ASP.Net

« Previous Next Chapter »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 43: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Examples in C# and VB

Learn ASP.NET Web Pages by C# and Visual Basic examples.

Examples in C# Examples in VB

Basic Web Pages

Display Date and TimeReusable Header and FooterBasic HTML Form

Examples Explained

Basic Web Pages

Display Date and TimeReusable Header and FooterBasic HTML Form

Examples Explained

Basic C#

For LoopFor Each LoopWhile LoopArray

If ConditionIf Else ConditionElse If ConditionSwitch Condition

Examples Explained

Basic VB

For LoopFor Each LoopWhile LoopArray

If ConditionIf Else ConditionElse If ConditionSelect Condition

Examples Explained

Working with Databases

Display Database DataDisplay Data with WebGrid

Examples Explained

Working with Databases

Display Database DataDisplay Data with WebGrid

Examples Explained

Using the Chart Helper

Display a Bar Chart from an ArrayDisplay a Bar Chart from a DatabaseDisplay a Pie Chart from a DatabaseDisplay a Pie Chart from an XML File

Examples Explained

Using the Chart Helper

Display a Bar Chart from an ArrayDisplay a Bar Chart from a DatabaseDisplay a Pie Chart from a DatabaseDisplay a Pie Chart from an XML File

Examples Explained

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 44: ASP.Net

Source: Output Result:

<html><body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p></body></html>

Hello Web PagesThe time is 7/22/2012 6:50:26 AM

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 45: ASP.Net

Source: Output Result:

<html><body>@RenderPage("header.cshtml")<h1>Hello Web Pages</h1> <p>This is a paragraph</p>@RenderPage("footer.cshtml")</body></html>

This is a header from a separate file

Hello Web PagesThis is a paragraph

This is a footer from a separate file

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 46: ASP.Net

Source: Output Result:

<html> <body> @{if (IsPost){ string companyname = Request["CompanyName"]; string contactname = Request["ContactName"]; <p>You entered: <br /> Company Name: @companyname <br /> Contact Name: @contactname </p> }else{<form method="post" action="">Company Name:<br /> <input type="text" name="CompanyName" value="" /><br/>Contact Name:<br /><br /><input type="text" name="ContactName" value="" /><br/><br /><input type="submit" value="Submit" class="submit" /></form> }} </body> </html>

Company Name:

Contact Name:

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 47: ASP.Net

Source: Output Result:

<html><body> <h1>Hello Web Pages</h1> <p>The time is @DateTime.Now</p></body></html>

Hello Web PagesThe time is 7/22/2012 6:51:45 AM

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 48: ASP.Net

Source: Output Result:

<html><body>@RenderPage("header.vbhtml")<h1>Hello Razor</h1> <p>This is a paragraph</p>@RenderPage("footer.vbhtml")</body></html>

This is a header from a separate file

Hello Web PagesThis is a paragraph

This is a footer from a separate file

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 49: ASP.Net

Source: Output Result:

<html> <body> @if (IsPost)Dim companyname = Request("CompanyName") Dim contactname = Request("ContactName") @<p>You entered: <br /><br />Company Name: @companyname <br /> Contact Name: @contactname </p> else@<form method="post" action=""> Company Name:<br /><input type="text" name="CompanyName" value="" /><br/>Contact Name:<br /><input type="text" name="ContactName" value="" /><br/><br /><input type="submit" value="Submit" class="submit" /> </form> end if

Company Name:

Contact Name:

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 50: ASP.Net

Source: Output Result:

<html><body>@for(var i = 10; i < 21; i++){<p>Line @i</p>}</body></html>

Line 10

Line 11

Line 12

Line 13

Line 14

Line 15

Line 16

Line 17

Line 18

Line 19

Line 20

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 51: ASP.Net

Source: Output Result:

<html><body><ul>@foreach (var x in Request.ServerVariables) {<li>@x</li>}</ul></body></html>

ALL_HTTPALL_RAWAPPL_MD_PATHAPPL_PHYSICAL_PATHAUTH_PASSWORDAUTH_TYPEAUTH_USERCERT_COOKIECERT_FLAGSCERT_ISSUERCERT_KEYSIZECERT_SECRETKEYSIZECERT_SERIALNUMBERCERT_SERVER_ISSUERCERT_SERVER_SUBJECTCERT_SUBJECTCONTENT_LENGTHCONTENT_TYPEGATEWAY_INTERFACEHTTPSHTTPS_KEYSIZEHTTPS_SECRETKEYSIZEHTTPS_SERVER_ISSUERHTTPS_SERVER_SUBJECTINSTANCE_IDINSTANCE_META_PATHLOCAL_ADDRLOGON_USERPATH_INFOPATH_TRANSLATEDQUERY_STRINGREMOTE_ADDRREMOTE HOST

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 52: ASP.Net

Source: Output Result:

<html><body>@{var i = 0;while (i < 5) { i += 1; <p>Line @i</p> }}</body></html>

Line 1

Line 2

Line 3

Line 4

Line 5

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 53: ASP.Net

Source: Output Result:

@{string[] members = {"Jani", "Hege", "Kai", "Jim"};int i = Array.IndexOf(members, "Kai")+1;int len = members.Length;string x = members[2-1];}<html><body><h3>Members</h3>@foreach (var person in members){<p>@person</p>}<p>The number of names in Members are @len</p><p>The person at position 2 is @x</p><p>Kai is now in position @i</p>

</body></html>

Members

Jani

Hege

Kai

Jim

The number of names in Members are 4

The person at position 2 is Hege

Kai is now in position 3

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 54: ASP.Net

Source: Output Result:

@{var price=50;}<html><body>@if (price>30) { <p>The price is too high</p> }</body></html>

The price is too high.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 55: ASP.Net

Source: Output Result:

@{var price=20;}<html><body>if (price>30) { <p>The price is too high.</p> } else { <p>The price is OK.</p> }</body></html>

The price is OK.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 56: ASP.Net

Source: Output Result:

@{var price=25;}<html><body>if (price>=30) { <p>The price is high.</p> } else if (price>20 && price<30) { <p>The price is OK.</p> } else { <p>The price is low.</p> }</body></html>

The price is OK.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 57: ASP.Net

Source: Output Result:

@{var message="";var weekday=DateTime.Now.DayOfWeek;var day=weekday.ToString()}<html><body>@switch(day){case "Monday": message="This is the first weekday."; break;case "Thursday": message="Only one day before weekend."; break;case "Friday": message="Tomorrow is weekend!"; break;default: message="Today is " + day; break;}<p>@message</p></body></html>

Today is Sunday

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 58: ASP.Net

Source: Output Result:

<html><body>@for i=10 to 21 @<p>Line @i</p>next i</body></html>

Line 10

Line 11

Line 12

Line 13

Line 14

Line 15

Line 16

Line 17

Line 18

Line 19

Line 20

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 59: ASP.Net

Source: Output Result:

<html><body><ul>@for each x in Request.ServerVariables @<li>@x</li>next x</ul></body></html>

ALL_HTTPALL_RAWAPPL_MD_PATHAPPL_PHYSICAL_PATHAUTH_PASSWORDAUTH_TYPEAUTH_USERCERT_COOKIECERT_FLAGSCERT_ISSUERCERT_KEYSIZECERT_SECRETKEYSIZECERT_SERIALNUMBERCERT_SERVER_ISSUERCERT_SERVER_SUBJECTCERT_SUBJECTCONTENT_LENGTHCONTENT_TYPEGATEWAY_INTERFACEHTTPSHTTPS_KEYSIZEHTTPS_SECRETKEYSIZEHTTPS_SERVER_ISSUERHTTPS_SERVER_SUBJECTINSTANCE_IDINSTANCE_META_PATHLOCAL_ADDRLOGON_USERPATH_INFOPATH_TRANSLATEDQUERY_STRINGREMOTE_ADDRREMOTE HOST

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 60: ASP.Net

Source: Output Result:

<html><body>@CodeDim i=0Do While i < 5 i += 1 @<p>Line @i</p>LoopEnd Code</body></html>

Line 1

Line 2

Line 3

Line 4

Line 5

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 61: ASP.Net

Source: Output Result:

@CodeDim members as String()={"Jani","Hege","Kai","Jim"}i=Array.IndexOf(members,"Kai")+1len=members.Lengthx=members(2-1)End Code<html><body><h3>Members</h3>@For Each person In members @<p>@person</p>Next person<p>The number of names in Members are @len</p><p>The person at position 2 is @x</p><p>Kai is now in position @i</p>

</body></html>

Members

Jani

Hege

Kai

Jim

The number of names in Members are 4

The person at position 2 is Hege

Kai is now in position 3

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 62: ASP.Net

Source: Output Result:

@CodeDim price=50End Code<html><body>@If price>30 Then@<p>The price is too high.</p>End If</body></html>

The price is too high.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 63: ASP.Net

Source: Output Result:

@CodeDim price=20End Code<html><body>@if price>30 Then @<p>The price is too high.</p>Else @<p>The price is OK.</p>End If</body></html>

The price is OK.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 64: ASP.Net

Source: Output Result:

@CodeDim price=25End Code<html><body>@if price>=30 Then @<p>The price is high.</p>ElseIf price>20 And price<30 then @<p>The price is OK.</p>Else @<p>The price is low.</p>End If</body></html>

The price is OK.

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 65: ASP.Net

Source: Output Result:

@CodeDim weekday=DateTime.Now.DayOfWeekDim day=weekday.ToString()Dim message=""End Code<html><body>@Select Case dayCase "Monday" message="This is the first weekday."Case "Thursday" message="Only one day before weekend."Case "Friday" message="Tomorrow is weekend!"Case Else message="Today is " & dayEnd Select<p>@message</p></body></html>

Today is Sunday

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 66: ASP.Net

Source: Output Result:

@{var db = Database.Open("SmallBakery"); var query = "SELECT * FROM Product"; }<html> <body> <h1>Small Bakery Products</h1> <table border="1" width="100%"> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@foreach(var row in db.Query(query)){<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td align="right">@row.Price</td> </tr> }</table> </body> </html>

Small Bakery ProductsId Product Description Price1 Bread Baked fresh every day 2.992 Strawberry Cake Made with organic strawberries 9.993 Apple Pie Second only to your mom's pie 12.994 Pecan Pie If you like pecans, this is for you 10.995 Lemon Pie Made with the best lemons in the world 11.996 Cupcakes Your kids will love these 9.99

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 67: ASP.Net

Source: Output Result:

@{ var db = Database.Open("SmallBakery") ; var query = "SELECT * FROM Product ORDER BY Id"; var data = db.Query(query); var grid = new WebGrid(data); }<html> <head> <title>Displaying Data Using the WebGridHelper</title> </head> <body> <h1>Small Bakery Products</h1> <div id="grid"> @grid.GetHtml()</div> </body> </html>

Small Bakery ProductsId Name Description Price1 Bread Baked fresh every day 2,993 Pecan Pie If you like pecans, this is for you 12,992 Strawberry Cake Made from organic strawberries 9,994 Lemon Pie Made with the best lemons in the world 11,995 Cupcakes Your kids will love yhese 7,99

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 68: ASP.Net

Source: Output Result:

@CodeDim db = Database.Open("SmallBakery") Dim query = "SELECT * FROM Product" End Code<html> <body> <h1>Small Bakery Products</h1> <table border="1" width="100%"> <tr><th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr>@CodeDim rowfor each row in db.Query(query)End Code<tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td align="right">@row.Price</td> </tr> @Code next End Code</table> </body> </html>

Small Bakery ProductsId Product Description Price1 Bread Baked fresh every day 2.992 Strawberry Cake Made with organic strawberries 9.993 Apple Pie Second only to your mom's pie 12.994 Pecan Pie If you like pecans, this is for you 10.995 Lemon Pie Made with the best lemons in the world 11.996 Cupcakes Your kids will love these 9.99

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 69: ASP.Net

Source: Output Result:

@Code Dim db = Database.Open("SmallBakery") Dim query = "SELECT * FROM Product" Dim data = db.Query(query) Dim grid = new WebGrid(data) End Code<html> <head> <title>Displaying Data Using the WebGridHelper</title> </head> <body> <h1>Small Bakery Products</h1> <div id="grid"> @grid.GetHtml()</div> </body> </html>

Small Bakery ProductsId Name Description Price1 Bread Baked fresh every day 2,993 Pecan Pie If you like pecans, this is for you 12,992 Strawberry Cake Made from organic strawberries 9,994 Lemon Pie Made with the best lemons in the world 11,995 Cupcakes Your kids will love yhese 7,99

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 70: ASP.Net

Source: Output Result:

@{ var myChart = new Chart(width: 600, height: 400) .AddTitle("Employees") .AddSeries(chartType: "column", xValue: new[] { "Peter", "Andrew", "Julie","Mary", "Dave" }, yValues: new[] { "2", "6", "4", "5", "3" }) .Write();}

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 71: ASP.Net

Source: Output Result:

@{ var db = Database.Open("SmallBakery"); var dbdata = db.Query("SELECT Name, Price FROMProduct"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Product Sales") .DataBindTable(dataSource: dbdata, xField: "Name") .Write();}

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 72: ASP.Net

Source: Output Result:

@{ var db = Database.Open("SmallBakery"); var dbdata = db.Query("SELECT Name, Price FROMProduct"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Product Sales") .AddSeries(chartType: "Pie", xValue: dbdata, xField: "Name", yValues: dbdata, yFields: "Price") .Write();}

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 73: ASP.Net

Source: Output Result:

@using System.Data;

@{var dataSet = new DataSet();dataSet.ReadXmlSchema(Server.MapPath("data.xsd"));dataSet.ReadXml(Server.MapPath("data.xml"));var dataView = new DataView(dataSet.Tables[0]);var myChart = new Chart(width: 600, height: 400) .AddTitle("Sales Per Employee") .AddSeries("Default", chartType: "Pie", xValue: dataView, xField: "Name", yValues: dataView, yFields: "Sales") .Write();}

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 74: ASP.Net

Source: Output Result:

@Code Dim myChart as new Chart(600,400)Dim xarr(4)xarr(0)="Peter"xarr(1)="Andrew"xarr(2)="Julie"xarr(3)="Mary"xarr(4)="Dave"Dim yarr(4)yarr(0)="2"yarr(1)="6"yarr(2)="4"yarr(3)="5"yarr(4)="3"myChart.AddTitle("Employees") myChart.AddSeries("Employees","column",,,,,xarr,,yarr,,

myChart.Write()End Code

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 75: ASP.Net

Source: Output Result:

@Code Dim db = Database.Open("SmallBakery") Dim dbdata = db.Query("SELECT Name, Price FROMProduct") Dim myChart = new Chart(600,400) myChart.AddTitle("Product Sales") myChart.DataBindTable(dbdata,"Name") myChart.Write()End Code

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 76: ASP.Net

Source: Output Result:

@Code Dim db = Database.Open("SmallBakery") Dim dbdata = db.Query("SELECT Name, Price FROMProduct") Dim myChart = new Chart(600,400) myChart.AddTitle("Product Sales") myChart.AddSeries("Employees","column",,,,,dbdata,"Name

myChart.Write()End Code

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 77: ASP.Net

Source: Output Result:

@Imports System.Data @CodeDim dataSet = new DataSet()dataSet.ReadXmlSchema(Server.MapPath("data.xsd"))dataSet.ReadXml(Server.MapPath("data.xml"))Dim dataView = new DataView(dataSet.Tables(0))Dim myChart = new Chart(600,400)myChart.AddTitle("Sales Per Employee")myChart.AddSeries("Default","Pie",,,,,dataView,"Name",d

myChart.Write()End Code

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 78: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Classes

ASP.NET Classes Reference

Method Description

AsBool(), AsBool(true|false) Converts a string value to a Boolean value (true/false). Returns false or thespecified value if the string does not represent true/false.

AsDateTime(), AsDateTime(value) Converts a string value to date/time. Returns DateTime. MinValue or thespecified value if the string does not represent a date/time.

AsDecimal(), AsDecimal(value) Converts a string value to a decimal value. Returns 0.0 or the specifiedvalue if the string does not represent a decimal value.

AsFloat(), AsFloat(value) Converts a string value to a float. Returns 0.0 or the specified value if thestring does not represent a decimal value.

AsInt(), AsInt(value) Converts a string value to an integer. Returns 0 or the specified value if thestring does not represent an integer.

Href(path [, param1 [, param2]]) Creates a browser-compatible URL from a local file path, with optionaladditional path parts.

Html.Raw(value) Renders value as HTML markup instead of rendering it as HTML-encodedoutput.

IsBool(), IsDateTime(), IsDecimal(), IsFloat(), IsInt() Returns true if the value can be converted from a string to the specifiedtype.

IsEmpty() Returns true if the object or variable has no value.

IsPost Returns true if the request is a POST. (Initial requests are usually a GET.)

Layout Specifies the path of a layout page to apply to this page.

PageData[key], PageData[index], Page Contains data shared between the page, layout pages, and partial pages inthe current request. You can use the dynamic Page property to access thesame data, as in the following example:

RenderBody() (Layout pages) Renders the content of a content page that is not in anynamed sections.

RenderPage(path, values) RenderPage(path[, param1 [, param2]])

Renders a content page using the specified path and optional extra data.You can get the values of the extra parameters from PageData by position(example 1) or key (example 2).

RenderSection(sectionName [, required = true|false]) (Layout pages) Renders a content section that has a name. Set required tofalse to make a section optional.

Request.Cookies[key] Gets or sets the value of an HTTP cookie.

Request.Files[key] Gets the files that were uploaded in the current request.

Request.Form[key] Gets data that was posted in a form (as strings). Request[key] checks boththe Request.Form and the Request.QueryString collections.

Request.QueryString[key] Gets data that was specified in the URL query string. Request[key] checksboth the Request.Form and the Request.QueryString collections.

Request.Unvalidated(key) Request.Unvalidated().QueryString|Form|Cookies|Headers[key]

Selectively disables request validation for a form element, query-stringvalue, cookie, or header value. Request validation is enabled by default andprevents users from posting markup or other potentially dangerous content.

Response.AddHeader(name, value) Adds an HTTP server header to the response.

Response.OutputCache(seconds [, sliding] [, varyByParams]) Caches the page output for a specified time. Optionally set sliding to resetthe timeout on each page access and varyByParams to cache differentversions of the page for each different query string in the page request.

Response.Redirect(path) Redirects the browser request to a new location.

Response.SetStatus(httpStatusCode) Sets the HTTP status code sent to the browser.

Response.WriteBinary(data [, mimetype]) Writes the contents of data to the response with an optional MIME type.

Response.WriteFile(file) Writes the contents of a file to the response.

@section(sectionName) { content } (Layout pages) Defines a content section that has a name.

Server.HtmlDecode(htmlText) Decodes a string that is HTML encoded.

Server.HtmlEncode(text) Encodes a string for rendering in HTML markup.

Server.MapPath(virtualPath) Returns the server physical path for the specified virtual path.

Server.UrlDecode(urlText) Decodes text from a URL.

Server.UrlEncode(text) Encodes text to put in a URL.

Session[key] Gets or sets a value that exists until the user closes the browser.

ToString() Displays a string representation of the object's value.

UrlData[index] Gets additional data from the URL (for example, /MyPage/ExtraData).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 79: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Pages - Database Object

ASP.NET Database Object Reference

Method Description

Database.Execute(SQLstatement [, parameters] Executes SQLstatement (with optional parameters) such as INSERT, DELETE,or UPDATE and returns a count of affected records.

Database.GetLastInsertId() Returns the identity column from the most recently inserted row.

Database.Open(filename) Database.Open(connectionStringName)

Opens either the specified database file or the database specified using anamed connection string from the Web.config file.

Database.OpenConnectionString(connectionString) Opens a database using the connection string. (This contrasts withDatabase.Open, which uses a connection string name.)

Database.Query(SQLstatement[, parameters]) Queries the database using SQLstatement (optionally passing parameters)and returns the results as a collection.

Database.QuerySingle(SQLstatement [, parameters]) Executes SQLstatement (with optional parameters) and returns a singlerecord.

Database.QueryValue(SQLstatement [, parameters]) Executes SQLstatement (with optional parameters) and returns a singlevalue.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 80: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - WebMail Object

With the WebMail object you can easily send emails from a web page.

DescriptionThe WebMail Object provides email for ASP.NET Web Pages using SMTP (Simple Mail Transfer Protocol).

ExampleSee an example in the chapter: Web Pages Email.

WebMail Object Reference - Properties

Properties Description

SmtpServer The name the SMTP server that will send the emails

SmtpPort The port the server will use to send SMTP emails

EnableSsl True, if the server should use SSL encryption

UserName The name of the SMTP account used to send the email

Password The password of the SMTP account

From The email to appear in the from address

WebMail Object Reference - Methods

Method Description

Send() Sends an email message to an SMTP server for delivery

The Send() method has the following parameters:

Parameter Type Description

to String The Email recipients (separated by semicolon)

subject String The subject line

body String The body of the message

And the following optional parameters:

Parameter Type Description

from String The email of the sender

cc String The cc emails (separated by semicolon)

filesToAttach Collection Filenames

isBodyHtml Boolean True if the email body is in HTML

additionalHeaders Collection Additional headers

Technical Data

Name Value

Class System.Web.Helpers.WebMail

Namespace System.Web.Helpers

Assembly System.Web.Helpers.dll

Initializing the WebMail HelperTo use the WebMail helper, you need access to an SMTP server. SMTP is the "output" part of email. If you use a web host, you probably already know thename of the SMTP server. If you work in a corporate network, your IT department can give you the name. If you are working at home, you might be able touse your ordinary email provider.

In order to send an email you will need:

The name of the SMTP serverThe port number (most often 25)An email user nameAn email password

In the root of your web, create a page (or edit the page ) named _AppStart.cshtml.

Put the following code inside the file:

_AppStart.cshtml

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 81: ASP.Net

« Previous Next Chapter »

@}WebMail.SmtpServer = "smtp.example.com";WebMail.SmtpPort = 25;WebMail.EnableSsl = false;WebMail.UserName = "[email protected]";WebMail.Password = "password";WebMail.From = "[email protected]"}

The code above will run each time the web site (application) starts. It feeds your WebMail Object with initial values.

Please substitute:

smtp.example.com with the name the SMTP server that will be used to send the emails.

25 with the port number the server will use to send SMTP transactions (emails).

false with true, if the server should use SSL (Secure Socket Layer) encryption.

[email protected] with the name of the SMTP email account used to send emails.

password with the password of the SMTP email account.

john@example with the email to appear in the from address.

You don't have to initiate the WebMail object in your AppStart file, but you must set these properties before you call the WebMail.Send() method.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 82: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - More Helpers

ASP.NET Helpers - Objects References

Analytics Object Reference (Google)

Helper Description

Analytics.GetGoogleHtml(webPropertyId) Renders the Google Analytics JavaScript code for the specified ID.

Analytics.GetStatCounterHtml(project, security) Renders the StatCounter Analytics JavaScript code for the specified project.

Analytics.GetYahooHtml(account) Renders the Yahoo Analytics JavaScript code for the specified account.

Bing Object Reference

Helper Description

Bing.SearchBox([boxWidth]) Passes a search to Bing. To specify the site to search and a title for thesearch box, you can set the Bing.SiteUrl and Bing.SiteTitle properties.Normally you set these properties in the _AppStart page.

Bing.AdvancedSearchBox([, boxWidth] [, resultWidth] [, resultHeight] [, themeColor] [, locale])

Displays Bing search results in the page with optional formatting. To specifythe site to search and a title for the search box, you can set the Bing.SiteUrland Bing.SiteTitle properties. Normally you set these properties in the_AppStart page.

Chart Object Reference

Helper Description

Chart(width, height [, template] [, templatePath]) Initializes a chart.

Chart.AddLegend([title] [, name]) Adds a legend to a chart.

Chart.AddSeries([name] [, chartType] [, chartArea] [, axisLabel] [, legend] [, markerStep] [, xValue] [, xField] [, yValues] [, yFields] [, options])

Adds a series of values to the chart.

Crypto Object Reference

Helper Description

Crypto.Hash(string [, algorithm]) Crypto.Hash(bytes [, algorithm])

Returns a hash for the specified data. The default algorithm is sha256.

Facebook Object Reference

Helper Description

Facebook.LikeButton(href [, buttonLayout] [, showFaces] [, width] [, height] [, action] [, font] [, colorScheme] [, refLabel])

Lets Facebook users make a connection to pages.

FileUpload Object Reference

Helper Description

FileUpload.GetHtml([initialNumberOfFiles] [, allowMoreFilesToBeAdded] [, includeFormTag] [, addText] [, uploadText])

Renders UI for uploading files.

GamerCard Object Reference

Helper Description

GamerCard.GetHtml(gamerTag) Renders the specified Xbox gamer tag.

Gravatar Object Reference

Helper Description

Gravatar.GetHtml(email [, imageSize] [, defaultImage] [, rating] [, imageExtension] [, attributes])

Renders the Gravatar image for the specified email address.

Json Object Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 83: ASP.Net

Helper Description

Json.Encode(object) Converts a data object to a string in the JavaScript Object Notation (JSON)format.

Json.Decode(string) Converts a JSON-encoded input string to a data object that you can iterateover or insert into a database.

LinkShare Object Reference

Helper Description

LinkShare.GetHtml(pageTitle [, pageLinkBack] [, twitterUserName] [, additionalTweetText] [, linkSites])

Renders social networking links using the specified title and optional URL.

ModelState Object Reference

Helper Description

ModelStateDictionary.AddError(key, errorMessage) Associates an error message with a form field. Use the ModelState helper toaccess this member.

ModelStateDictionary.AddFormError(errorMessage) Associates an error message with a form. Use the ModelState helper toaccess this member.

ModelStateDictionary.IsValid Returns true if there are no validation errors. Use the ModelState helper toaccess this member.

ObjectInfo Object Reference

Helper Description

ObjectInfo.Print(value [, depth] [, enumerationLength]) Renders the properties and values of an object and any child objects.

Recaptcha Object Reference

Helper Description

Recaptcha.GetHtml([, publicKey] [, theme] [, language] [, tabIndex]) Renders the reCAPTCHA verification test.

ReCaptcha.PublicKey ReCaptcha.PrivateKey

Sets public and private keys for the reCAPTCHA service. Normally you setthese properties in the _AppStart page.

ReCaptcha.Validate([, privateKey]) Returns the result of the reCAPTCHA test.

ServerInfo.GetHtml() Renders status information about ASP.NET Web Pages.

Twitter Object Reference

Helper Description

Twitter.Profile(twitterUserName) Renders a Twitter stream for the specified user.

Twitter.Search(searchQuery) Renders a Twitter stream for the specified search text.

Video Object Reference

Helper Description

Video.Flash(filename [, width, height]) Renders a Flash video player for the specified file with optional width andheight.

Video.MediaPlayer(filename [, width, height]) Renders a Windows Media player for the specified file with optional widthand height.

Video.Silverlight(filename, width, height) Renders a Silverlight player for the specified .xap file with required widthand height.

WebCache Object Reference

Helper Description

WebCache.Get(key) Returns the object specified by key, or null if the object is not found.

WebCache.Remove(key) Removes the object specified by key from the cache.

WebCache.Set(key, value [, minutesToCache] [, slidingExpiration]) Puts value into the cache under the name specified by key.

WebGrid Object Reference

Helper Description

WebGrid(data) Creates a new WebGrid object using data from a query.

WebGrid.GetHtml() Renders markup to display data in an HTML table.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 84: ASP.Net

« Previous Next Chapter »

WebGrid.Pager() Renders a pager for the WebGrid object.

WebImage Object Reference

Helper Description

WebImage(path) Loads an image from the specified path.

WebImage.AddImagesWatermark(image) Adds the specified image as a watermark.

WebImage.AddTextWatermark(text) Adds the specified text to the image.

WebImage.FlipHorizontal() WebImage.FlipVertical()

Flips the image horizontally or vertically.

WebImage.GetImageFromRequest() Loads an image when an image is posted to a page during a file upload.

WebImage.Resize(width, height) Resizes the image.

WebImage.RotateLeft() WebImage.RotateRight()

Rotates the image to the left or the right.

WebImage.Save(path [, imageFormat]) Saves the image to the specified path.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 85: ASP.Net

« Previous Next Chapter »

ASP.NET Web Pages - WebSecurity Object

DescriptionThe WebSecurity Object provides security and authentication for ASP.NET Web Pages applications.

With the WebSecurity object you can create user accounts, login and logout users, reset or changepasswords, and more.

WebSecurity Object Reference - Properties

Properties Description

CurrentUserId Gets the ID for the current user

CurrentUserName Gets the name of the current user

HasUserId Returns true if the current has a user ID

IsAuthenticated Returns true if the current user is logged in

WebSecurity Object Reference - Methods

Method Description

ChangePassword() Changes the password for a user

ConfirmAccount() Confirms an account using a confirmation token

CreateAccount() Creates a new user account

CreateUserAndAccount() Creates a new user account

GeneratePasswordResetToken() Generates a token that can be sent to as user by email

GetCreateDate() Gets the time the specified membership was created

GetPasswordChangeDate() Gets the date and time when password was changed

GetUserId() Gets a user ID from a user name

InitializeDatabaseConnection() Initializes the WebSecurity system (database)

IsConfirmed() Checks if a user is confirmed

IsCurrentUser() Checks if the current user matches a user name

Login() Logs the user in by setting a token in the cookie

Logout() Logs the user out by removing the token cookie

RequireAuthenticatedUser() Exits the page if the user is not an authenticated user

RequireRoles() Exits the page if the user is not a part of the specified roles

RequireUser() Exits the page if the user is not the specified user

ResetPassword() Changes a user's password using a token

UserExists() Checks if a given user exists

Technical Data

Name Value

Class WebMatrix.WebData.WebSecurity

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

Initializing the WebSecurity DatabaseYou must create or initialize an WebSecurity database before you can use the WebSecurity object inyour code.

In the root of your web, create a page (or edit the page ) named _AppStart.cshtml.

Put the following code inside the file:

_AppStart.cshtml

@{WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId","Email", true);}

The code above will run each time the web site (application) starts. It initializes the WebSecuritydatabase.

"Users" is the name of the WebSecurity database (Users.sdf).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 86: ASP.Net

« Previous Next Chapter »

"UserProfile" is the name of the database table that contains the user profile information.

"UserId" is the name of the column that contains the user IDs (primary key).

"Email" is the name of the column that contains user names.

The last parameter true is a boolean value indicating that the user profile and membership tablesshould be created automatically if they don't exist, otherwise false.

Although true indicates automatic creation of the database tables, the database itself will notbe created automatically. It must exist.

The WebSecurity DatabaseThe UserProfile table contains one record for each user, with a user ID (primary key) and the user'sname (email):

UserId Email

1 [email protected]

2 [email protected]

3 [email protected]

The Membership table will contain membership information about when the user was created and if(and when) the membership was confirmed.

Much like this (some columns are not shown):

UserId

CreateDate

ConfirmationToken

IsConfirmed

LastPasswordFailure

Password PasswordChange

1 12.04.201216:12:17

NULL True NULL AFNQhWfy.... 12.04.201216:12:17

Note: If you want to see all columns and all content, open the database with WebMatrix and look insideeach table.

Simple Membership ConfigurationYou might get errors using the WebSecurity object, if your site is not configured to use the ASP.NETWeb Pages membership system SimpleMembership.

This can occur if a hosting provider's server is configured differently than your local server. To fix this,add the following element to the site's Web.config file:

<appSettings> <add key="enableSimpleMembership" value="true" /> </appSettings>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 87: ASP.Net

WebSecurity Property - CurrentUserId

WebSecurity Object

DefinitionThe CurrentUserId property is the ID (primary key) for the current user in the WebSecuritydatabase.

C# and VB Syntax

WebSecurity.CurrentUserId

Examples

Example C#

@{int value;value=WebSecurity.CurrentUserId;}

<p>Current User ID is: @value</p>

Example VB

@CodeDim value as Integervalue=WebSecurity.CurrentUserIdEnd Code

<p>Current User ID is: @value</p>

RemarksThe CurrentUserId property is read only. It cannot be changed by code.

The property is used to identify the user in the WebSecurity database, both in the user profile tableand in the membership table.

Errors and ExceptionsThe CurrentUserId property returns -1 if there is no current user logged in.

Any access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 88: ASP.Net

WebSecurity Property - CurrentUserName

WebSecurity Object

DefinitionThe CurrentUserName property is the name of the current user in the user profile table in the WebSecurity database.

C# and VB Syntax

WebSecurity.CurrentUserName

Examples

Example C#

@{string value;value=WebSecurity.CurrentUserId;}

<p>Welcome @value</p>

Example VB

@CodeDim value as Stringvalue=WebSecurity.CurrentUserNameEnd Code

<p>Welcome @value</p>

RemarksThe CurrentUserName property is read only. It cannot be changed by code.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 89: ASP.Net

WebSecurity Property - HasUserId

WebSecurity Object

DefinitionThe HasUserId property is a boolean value that indicates whether the current user has a user ID inthe WebSecurity database.

The property value is a boolean true if the current user has a user ID. The default is false.

C# and VB Syntax

WebSecurity.HasUserId

Examples

Example C#

@{bool value;value=WebSecurity.HasUserId;}<p>It is @value that the user has an ID</p>

Example VB

@CodeDim value as Booleanvalue=WebSecurity.HasUserIdEnd Code

<p>It is @value that the user has an ID</p>

RemarksThe HasUserID property is read only. It cannot be changed by code.

The HasUserId property only verifies that the user has an ID in the WebSecurity database. It doesnot verify that the user account is valid (confirmed), or that the user is logged in.

Use the IsConfirmed() method to verify that the user is confirmed.

Use IsAuthenticated property to verify that the user is logged in.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 90: ASP.Net

WebSecurity Property - IsAuthenticated

WebSecurity Object

DefinitionThe IsAuthenticated property is a boolean value that indicates whether the current user isauthenticated (logged in).

The property value is a boolean true if the current user is authenticated, otherwise false.

C# and VB Syntax

WebSecurity.IsAuthenticated

Examples

Example C#

if (!WebSecurity.IsAuthenticated){Response.Redirect("~/Account/Login");}

Example VB

if !WebSecurity.IsAuthenticated then Response.Redirect("~/Account/Login")end if

RemarksThe IsAuthenticated property is read only. It cannot be changed by code.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 91: ASP.Net

WebSecurity - ChangePassword()

WebSecurity Object

DefinitionThe ChangePassword() method changes the password for a specified user.

Syntax in C# and VB

WebSecurity.ChangePassword(userName, oldPassword, newPassword)

Parameters

Parameter Type Description

userName String The user name

oldPassword String The user's old password

newPassword String The new password

Return Value

Type Description

Boolean true if the password is changed, otherwise false

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 92: ASP.Net

WebSecurity - ConfirmAccount()

WebSecurity Object

DefinitionThe ConfirmAccount() method confirms and activates an account using a confirmation token.

C# and VB Syntax

WebSecurity.ConfirmAccount(accountConfirmationToken)

Examples

Example C#

string message = "";var confirmationToken = Request["confirmationCode"];

WebSecurity.Logout();

if (!confirmationToken.IsEmpty()){ if (WebSecurity.ConfirmAccount(confirmationToken)) { message = "Registration confirmed"; } else { message = "Could not confirm your registration"; }}

Example VB

message = ""confirmationToken = Request("confirmationCode")

WebSecurity.Logout()

if !confirmationToken.IsEmpty() then if WebSecurity.ConfirmAccount(confirmationToken) then message = "Registration Confirmed" else message = "Could not confirm your registration" end if end if

Parameters

Parameter Type Description

accountConfirmationToken String The confirmation tokene

Return Value

Type Description

Boolean true if the account is confirmed, otherwise false.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksA confirmation token can be created by the CreateAccount(), CreateUserAndAccount(), orGeneratePasswordResetToken() methods.

Common procedure is to send the token to a user in an email, and ask the user to verify the identity(via a link to a confirmation page).

Technical Data

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 93: ASP.Net

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 94: ASP.Net

WebSecurity - CreateAccount()

WebSecurity Object

DefinitionThe CreateAccount() method creates a new account in the user database, using user name andpassword, and optionally lets you specify if the user must explicitly confirm the account.

C# and VB Syntax

WebSecurity.CreateAccount(username, password, requireConfirmation)

Parameters

Parameter Type Description

userName String The user name

password String The user password

requireConfirmation Boolean true if the account must be confirmed using the tokenreturn value, default is false.

Return Value

Type Description

String A token that can be sent to the user to confirm the account.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

The CreateAccount() method also throws a MembershipCreateUserException if:

The username is emptyThe username already has a membership accountThe password is emptyThe password is too longThe database operation failed

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 95: ASP.Net

WebSecurity - CreateUserAndAccount()

WebSecurity Object

DefinitionThe CreateUserAndAccount() method creates a new account in the user database, using user nameand password, and optionally lets you specify if the user must explicitly confirm the account.

C# and VB Syntax

WebSecurity.CreateUserAndAccount(username, password, propertyValues,requireConfirmation)

Parameters

Parameter Type Description

userName String The user name

password String The user password

propertyValues Object A dictionary that contains additional user attributes

requireConfirmation Boolean true if the account must be confirmed using the tokenreturn value, default is false.

Return Value

Type Description

String A token that can be sent to the user to confirm the account.

RemarksThe CreateUserAndAccount() method creates a new entry in the user profile table and then acorresponding entry in the membership table in the WebSecurity database.

You can pass true for requireConfirmationToken parameter to require that the user account mustbe confirmed by the user. To confirm the account, you get the token as the return value from theCreateUserAndAccount() method.

If you are manually maintaining the user profile table and only want to create a membership tableentry for the user, call the CreateAccount() method instead.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

The CreateUserAndAccount() method also throws a MembershipCreateUserException if:

The username is emptyThe username already has a membership accountThe password is emptyThe password is too longThe database operation failed

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 96: ASP.Net

WebSecurity - GeneratePasswordResetToken()

WebSecurity Object

DefinitionThe GeneratePasswordResetToken() method generates a password reset token that can be sent toa user in email.

C# and VB Syntax

WebSecurity.GeneratePasswordResetToken(userName, expiration)

Parameters

Parameter Type Description

userName String The user name

expiration Integer The time in minutes until the token expires. Default is 1440(24 hours)

Return Value

Type Description

String A reset token.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksUse the ResetPassword() method if the user has forgotten his password. The ResetPassword()method requires a password reset token.

A confirmation token can be created by the CreateAccount(), CreateUserAndAccount(), orGeneratePasswordResetToken() methods.

The password can be reset by code, but the common procedure is to send an email to the user (withthe token and a link to a page) so he can confirm the new password with the new token:

@{newPassword = Request["newPassword"];confirmPassword = Request["confirmPassword"];token = Request["token"];if isPost{ // input testing is ommitted here to save space retunValue = ResetPassword(token, newPassword); }}<h1>Change Password</h1>

<form method="post" action="">

<label for="newPassword">New Password:</label> <input type="password" id="newPassword" name="newPassword" title="Newpassword" />

<label for="confirmPassword">Confirm Password:</label> <input type="password" id="confirmPassword" name="confirmPassword"title="Confirm new password" />

<label for="token">Pasword Token:</label> <input type="text" id="token" name="token" title="Password Token" />

<p class="form-actions"><input type="submit" value="Change Password" title="Change password" /></p>

</form>

Technical Data

Name Value

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 97: ASP.Net

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 98: ASP.Net

WebSecurity - GetCreateDate()

WebSecurity Object

Definition and UseThe GetCreateDate() method returns the date and time when the specified membership account was created.

C# and VB Syntax

WebSecurity.GetCreateDate(userName)

Parameters

Parameter Type Description

userName String The user name

Return Value

Type Description

DateTime The date and time the membership account was created

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

If the account creation date is not available, the GetCreatedDate() method returns DateTime.MinValue.

The value of DateTime.MinValue is 00:00:00.0000000, January 1, 0001.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 99: ASP.Net

WebSecurity - GetPasswordChangeDate()

WebSecurity Object

DefinitionThe GetPasswordChangeDate() method returns the date and time a user's password was lastchanged.

C# and VB Syntax

WebSecurity.GetPasswordChangedDate(userName)

Parameters

Parameter Type Description

userName String The user name

Return Value

Type Description

DateTime The date and time the password was last changed

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksIf the password has never been changed, the GetPasswordChangeDate() method returnsDateTime.MinValue.

The value of DateTime.MinValue is 00:00:00.0000000, January 1, 0001.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 100: ASP.Net

WebSecurity - GetUserId()

WebSecurity Object

DefinitionThe GetUserId() method returns the ID for the specified user.

C# and VB Syntax

WebSecurity.GetUserId(userName)

Parameters

Parameter Type Description

userName String The user name

Return Value

Type Description

Integer The user ID

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksThe user ID is the primary key for the user information stored in the user database.

It is used to identify the user, both in the user profile table and in the membership table.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 101: ASP.Net

WebSecurity - InitializeDatabaseConnection()

WebSecurity Object

DefinitionThe InitializeDatabaseConnection() method initializes the WebSecurity database.

The method initializes the WebSecurity system by connecting to the database that contains user andmembership information.

C# and VB Syntax

WebSecurity.InitializeDatabaseConnection(connectionString, userTableName,userIdColumn, userNameColumn, autoCreateTables)

Parameters

Parameter Type Description

connectionString String The name of your WebSecurity database (se remarks)

userTableName String The database table that contains the user profileinformation

userIdColumn String The database column that contains the user IDs (primarykeys)

userNameColumn String The database column that contains the user names

autoCreateTables Boolean true indicates that user profile and membership tablesshould be created if they do not exist, otherwise false

Return ValueNone.

RemarksIf you are using SQL Server Compact, connectionString should be the name of the WebSecuritydatabase (without the .sdf file name extension). Otherwise it should be the name of a connection stringin the web configuration (web.config file).

Even if autoCreateTables can force the database tables to be created automatically, thedatabase itself must always exist.

Errors and ExceptionsThe InitializeDatabaseConnection() method throws an InvalidOperationException if:

SimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 102: ASP.Net

WebSecurity - IsConfirmed()

WebSecurity Object

DefinitionThe IsConfirmed() method returns a value that indicates whether the specified user has beenconfirmed.

C# and VB Syntax

WebSecurity.IsConfirmed(userName);

Parameters

Parameter Type Description

userName String The user name

Return Value

Type Description

Boolean true if the user is confirmed, otherwise false

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksThe IsConfirmed() method checks the user account identified by the userName parameter.

If the membership has been confirmed (the user has confirmed the account by clicking an email link),the method returns true.

If a registration has not been confirmed, the user cannot log in.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 103: ASP.Net

WebSecurity - Login()

WebSecurity Object

DefinitionThe Login() method logs in a specified user, using a username and a password.

C# and VB Syntax

WebSecurity.Login(userName, password, persistCookie)

Examples

Example C#

if (WebSecurity.Login(username,password)){<p>Welcome</p>}else{<p>Incorrect username or password.</p>}

Example VB

if WebSecurity.Login(username,password)<p>Welcome</p>else<p>Incorrect username or password</p>end if

Parameters

Parameter Type Description

userName String The user name

password String The user password

persistCookie String true to specify that the authentication token in the cookieshould be persisted beyond the current session; otherwisefalse. Default is false.

Return Value

Type Description

Boolean true if the user is logged in, otherwise false

RemarksWhen a user is logged in, ASP.NET sets an authentication token in a cookie that lets ASP.NET know onsubsequent requests that the user has been logged in. If persistCookie is false, the token is validonly until the user closes the browser.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 104: ASP.Net

WebSecurity - Logout()

WebSecurity Object

DefinitionThe Logout() method logs out the current user.

C# and VB Syntax

Logout()

Examples

Example C#

// Log out the current userWebSecurity.Logout();

// Redirect back to the homepageResponse.Redirect("~/");

Example VB

' Log out the current userWebSecurity.Logout()

' Redirect back to the homepageResponse.Redirect("~/")

ParametersNone.

Return ValueNone.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksWhen a user is logged in, ASP.NET sets an authentication token in a cookie that lets ASP.NET know on subsequent requests that the user has been loggedin.

The Logout() method removes the authentication token, which has the effect of logging the user out.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 105: ASP.Net

WebSecurity - RequireAuthenticatedUser()

WebSecurity Object

DefinitionThe RequireAuthenticatedUser() method sets the HTTP status to 401 (Unauthorized) if the currentuser is not authenticated.

C# and VB Syntax

WebSecurity.RequireAuthenticatedUser()

ParametersNone.

Return ValueNone.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksRequireAuthenticatedUser() only validates if the current user is authenticated. If the current user isnot authenticated, the HTTP status is set to 401 (Unauthorized).

To validate if the current user is a specific user (by ID or by name), use the RequireUser() method.To validate that a user is a member of a role (roles), use the RequireRoles() method.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 106: ASP.Net

WebSecurity - RequireRoles()

WebSecurity Object

DefinitionThe RequireRoles() method sets the HTTP status to 401 (Unauthorized) if the current user is not inall of the specified roles.

C# and VB Syntax

WebSecurity.RequireRoles(roles)

Examples

Example C#

WebSecurity.RequireRoles("Admin", "Poweruser");

Example VB

WebSecurity.RequireRoles("Admin", "Poweruser")

Parameters

Parameter Type Description

roles String A comma separated list of roles the current user must be in.

Return ValueNone.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksRequireRoles() validates that the current user is a member of all of the specified roles. If the user isnot a member of all of the specified roles, the HTTP status is set to 401 (Unauthorized).

To validate that the user is authenticated, use the RequireAuthenticatedUser() method.

To validate that the current user is a specific user, use the RequireUser() method.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 107: ASP.Net

WebSecurity - RequireUser()

WebSecurity Object

DefinitionThe RequireUser() method sets the HTTP status to 401 (Unauthorized) if the specified user is notlogged on.

C# and VB Syntax

WebSecurity.RequireUser(userId)

or

WebSecurity.RequireUser(userName)

Parameters

Parameter Type Description

userID Integer The user ID

userName String The user name

Return ValueNone.

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksRequireUser() verifies that the current user is the specified user.

To validate that the user is authenticated, use RequireAuthenticatedUser() instead.

To validate that a user is a member of a role (roles), use RequireRoles().

RequireUser() lets only the specified user access the web page. The recommended way to restrictaccess to a page is to create a role, and use the RequireRoles() method to verify that the user is amember of that role.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 108: ASP.Net

WebSecurity - ResetPassword()

WebSecurity Object

DefinitionThe ResetPassword() method resets a user password using a password token.

C# and VB Syntax

WebSecurity.ResetPassword(passwordResetToken,newPassword)

Parameters

Parameter Type Description

passwordResetToken String The password token

newpassword String The new password

Return Value

Type Description

Boolean true if the password was changed, otherwise false

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksUse the ResetPassword method if the user has forgotten his password.

The ResetPassword method requires a password reset token.

A confirmation token can be created by the CreateAccount(), CreateUserAndAccount(), or GeneratePasswordResetToken() methods.

The password can be reset by code, but the common procedure is to send an email to the user (with the token and a link to a page) so he can confirm thenew password with the new token:

@{newPassword = Request["newPassword"];confirmPassword = Request["confirmPassword"];token = Request["token"];if isPost{ // input testing is ommitted here to save space retunValue = ResetPassword(token, newPassword); }}<h1>Change Password</h1>

<form method="post" action="">

<label for="newPassword">New Password:</label> <input type="password" id="newPassword" name="newPassword" title="Newpassword" />

<label for="confirmPassword">Confirm Password:</label> <input type="password" id="confirmPassword" name="confirmPassword"title="Confirm new password" />

<label for="token">Pasword Token:</label> <input type="text" id="token" name="token" title="Password Token" />

<p class="form-actions"><input type="submit" value="Change Password" title="Change password" /></p>

</form>

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 109: ASP.Net

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 110: ASP.Net

WebSecurity - UserExists()

WebSecurity Object

DefinitionThe UserExists() method indicates if the user exists in the WebSecurity database.

C# and VB Syntax

WebSecurity.UserExists(userName)

Parameters

Parameter Type Description

userName String The user name

Return Value

Type Description

Boolean true if the user exists, otherwise false

Errors and ExceptionsAny access to the WebSecurity object throws an InvalidOperationException if:

The InitializeDatabaseConnection() method has not been calledSimpleMembership is not initialized (or disabled in the website configuration)

RemarksThe UserExists() method only verifies that the user exists in the user profile table.

It does not verify that a membership account exists for that user, or that the user is confirmed, orlogged in.

Technical Data

Name Value

Namespace WebMatrix.WebData

Assembly WebMatrix.WebData.dll

WebSecurity Object

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 111: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Razor - Markup

Razor is not a programming language. It's a server side markup language.

What is Razor?Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.

Server-based code can create dynamic web content on the fly, while a web page is written to the browser. When a web page is called, the server executesthe server-based code inside the page before it returns the page to the browser. By running on the server, the code can perform complex tasks, likeaccessing databases.

Razor is based on ASP.NET, and designed for creating web applications. It has the power of traditional ASP.NET markup, but it is easier to use, and easier tolearn.

Razor SyntaxRazor uses a syntax very similar to PHP and Classic ASP.

Razor:

<ul>@for (int i = 0; i < 10; i++) {<li>@i</li>}</ul>

PHP:

<ul><?php for ($i = 0; $i < 10; $i++) {echo("<li>$i</li>");} ?></ul>

Web Forms (and Classic ASP):

<ul><% for (int i = 0; i < 10; i++) { %><li><% =i %></li><% } %></ul>

Razor HelpersASP.NET helpers are components that can be accessed by single lines of Razor code.

You can build your own helpers using Razor syntax, or use built-in ASP.NET helpers.

Below is a short description of some useful Razor helpers:

Web GridWeb GraphicsGoogle AnalyticsFacebook IntegrationTwitter IntegrationSending EmailValidation

Razor Programming LanguagesRazor supports both C# (C sharp) and VB (Visual Basic).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 112: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - C# and VB Code Syntax

Razor supports both C# (C sharp) and VB (Visual Basic).

Main Razor Syntax Rules for C#Razor code blocks are enclosed in @{ ... }Inline expressions (variables and functions) start with @Code statements end with semicolonVariables are declared with the var keywordStrings are enclosed with quotation marksC# code is case sensitiveC# files have the extension .cshtml

C# Example

<!-- Single statement block -->@{ var myMessage = "Hello World"; }

<!-- Inline expression or variable --><p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->@{var greeting = "Welcome to our site!";var weekDay = DateTime.Now.DayOfWeek;var greetingMessage = greeting + " Today is: " + weekDay;}<p>The greeting is: @greetingMessage</p>

Run example »

Main Razor Syntax Rules for VBRazor code blocks are enclosed in @Code ... End CodeInline expressions (variables and functions) start with @Variables are declared with the Dim keywordStrings are enclosed with quotation marksVB code is not case sensitiveVB files have the extension .vbhtml

Example

<!-- Single statement block --> @Code dim myMessage = "Hello World" End Code <!-- Inline expression or variable --> <p>The value of myMessage is: @myMessage</p> <!-- Multi-statement block --> @Codedim greeting = "Welcome to our site!" dim weekDay = DateTime.Now.DayOfWeek dim greetingMessage = greeting & " Today is: " & weekDayEnd Code

<p>The greeting is: @greetingMessage</p>

Run example »

How Does it Work?Razor is a simple programming syntax for embedding server code in web pages.

Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that'sspecifically designed for creating web applications.

The Razor syntax gives you all the power of ASP.NET, but is using a simplified syntax that's easier tolearn if you're a beginner, and makes you more productive if you're an expert.

Razor web pages can be described as HTML pages with two kinds of content: HTML content and Razorcode.

When the server reads the page, it runs the Razor code first, before it sends the HTML page to thebrowser. The code that is executed on the server can perform tasks that cannot be done in thebrowser, for example accessing a server database. Server code can create dynamic HTML content onthe fly, before it is sent to the browser. Seen from the browser, the HTML generated by server code isno different than static HTML content.

ASP.NET web pages with Razor syntax have the special file extension cshtml (Razor using C#) orvbhtml (Razor using VB).

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 113: ASP.Net

Working With ObjectsServer coding often involves objects.

The "Date" object is a typical built-in ASP.NET object, but objects can also be self-defined, a web page,a text box, a file, a database record, etc.

Objects may have methods they can perform. A database record might have a "Save" method, animage object might have a "Rotate" method, an email object might have a "Send" method, and so on.

Objects also have properties that describe their characteristics. A database record might have aFirstName and a LastName property (amongst others).

The ASP.NET Date object has a Now property (written as Date.Now), and the Now property has a Dayproperty (written as Data.Now.Day). The example below shows how to access some properties of theDate object:

Example

<table border="1"><tr><th width="100px">Name</th><td width="100px">Value</td></tr><tr><td>Day</td><td>@DateTime.Now.Day</td></tr><tr><td>Hour</td><td>@DateTime.Now.Hour</td></tr><tr><td>Minute</td><td>@DateTime.Now.Minute</td></tr><tr><td>Second</td><td>@DateTime.Now.Second</td></tr></td></table>

Run example »

If and Else ConditionsAn important feature of dynamic web pages is that you can determine what to do based on conditions.

The common way to do this is with the if ... else statements:

Example

@{var txt = "";if(DateTime.Now.Hour > 12) {txt = "Good Evening";}else {txt = "Good Morning";}}<html><body><p>The message is @txt</p></body></html>

Run example »

Reading User InputAnother important feature of dynamic web pages is that you can read user input.

Input is read by the Request[] function, and posting (input) is tested by the IsPost condition:

Example

@{var totalMessage = "";if(IsPost) { var num1 = Request["text1"]; var num2 = Request["text2"]; var total = num1.AsInt() + num2.AsInt(); totalMessage = "Total = " + total; }}<html><body style="background-color: beige; font-family: Verdana, Arial;"><form action="" method="post"><p><label for="text1">First Number:</label><br><input type="text" name="text1" /></p><p><label for="text2">Second Number:</label><br><input type="text" name="text2" /></p><p><input type="submit" value=" Add " /></p>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 114: ASP.Net

« Previous Next Chapter »

</form><p>@totalMessage</p></body></html>

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 115: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - C# Variables

Variables are named entities used to store data.

VariablesVariables are used to store data.

The name of a variable must begin with an alphabetic character and cannot contain whitespace or reserved characters.

A variable can be of a specific type, indicating the kind of data it stores. String variables store string values ("Welcome to W3Schools"), integer variablesstore number values (103), date variables store date values, etc.

Variables are declared using the var keyword, or by using the type (if you want to declare the type), but ASP.NET can usually determine data typesautomatically.

Examples

// Using the var keyword:var greeting = "Welcome to W3Schools";var counter = 103;var today = DateTime.Today;

// Using data types:string greeting = "Welcome to W3Schools";int counter = 103;DateTime today = DateTime.Today;

Data TypesBelow is a list of common data types:

Type Description Examples

int Integer (whole numbers) 103, 12, 5168

float Floating-point number 3.14, 3.4e38

decimal Decimal number (higher precision) 1037.196543

bool Boolean true, false

string String "Hello W3Schools", "John"

OperatorsAn operator tells ASP.NET what kind of command to perform in an expression.

The C# language supports many operators. Below is a list of common operators:

Operator Description Example

= Assigns a value to a variable. i=6

+-*/

Adds a value or variable.Subtracts a value or variable.Multiplies a value or variable.Divides a value or variable.

i=5+5i=5-5i=5*5i=5/5

+=-=

Increments a variable.Decrements a variable.

i += 1i -= 1

== Equality. Returns true if values are equal. if (i==10)

!= Inequality. Returns true if values are not equal. if (i!=10)

<><=>=

Less than.Greater than.Less than or equal.Greater than or equal.

if (i<10)if (i>10)if (i<=10)if (i>=10)

+ Adding strings (concatenation). "w3" + "schools"

. Dot. Separate objects and methods. DateTime.Hour

() Parenthesis. Groups values. (i+5)

() Parenthesis. Passes parameters. x=Add(i,5)

[] Brackets. Accesses values in arrays or collections. name[3]

! Not. Reverses true or false. if (!ready)

&&||

Logical AND.Logical OR.

if (ready && clear)if (ready || clear)

Converting Data TypesConverting from one data type to another is sometimes useful.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 116: ASP.Net

« Previous Next Chapter »

The most common example is to convert string input to another type, such as an integer or a date.

As a rule, user input comes as strings, even if the user entered a number. Therefore, numeric input values must be converted to numbers before they canbe used in calculations.

Below is a list of common conversion methods:

Method Description Example

AsInt()IsInt()

Converts a string to an integer. if (myString.IsInt()) {myInt=myString.AsInt();}

AsFloat()IsFloat()

Converts a string to a floating-point number. if (myString.IsFloat()) {myFloat=myString.AsFloat();}

AsDecimal()IsDecimal()

Converts a string to a decimal number. if (myString.IsDecimal()) {myDec=myString.AsDecimal();}

AsDateTime()IsDateTime()

Converts a string to an ASP.NET DateTime type. myString="10/10/2012";myDate=myString.AsDateTime();

AsBool()IsBool()

Converts a string to a Boolean. myString="True";myBool=myString.AsBool();

ToString() Converts any data type to a string. myInt=1234;myString=myInt.ToString();

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 117: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - C# Loops and Arrays

Statements can be executed repeatedly in loops.

For LoopsIf you need to run the same statements repeatedly, you can program a loop.

If you know how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:

Example

<html><body>@for(var i = 10; i < 21; i++) {<p>Line @i</p>}</body></html>

Run example »

For Each LoopsIf you work with a collection or an array, you often use a for each loop.

A collection is a group of similar objects, and the for each loop lets you carry out a task on each item. The for each loop walks through a collection until it isfinished.

The example below walks through the ASP.NET Request.ServerVariables collection.

Example

<html><body><ul>@foreach (var x in Request.ServerVariables) {<li>@x</li>}</ul></body></html>

Run example »

While LoopsThe while loop is a general purpose loop.

A while loop begins with the while keyword, followed by parentheses, where you specify how long the loop continues, then a block to repeat.

While loops typically add to, or subtract from, a variable used for counting.

In the example below, the += operator adds 1 to the variable i, each time the loop runs.

Example

<html><body>@{var i = 0;while (i < 5) { i += 1; <p>Line #@i</p> }}</body></html>

Run example »

ArraysAn array is useful when you want to store similar variables but don't want to create a separate variable for each of them:

Example

@{string[] members = {"Jani", "Hege", "Kai", "Jim"};int i = Array.IndexOf(members, "Kai")+1;

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 118: ASP.Net

« Previous Next Chapter »

int len = members.Length;string x = members[2-1];}<html><body><h3>Members</h3>@foreach (var person in members){<p>@person</p>}<p>The number of names in Members are @len</p><p>The person at position 2 is @x</p><p>Kai is now in position @i</p></body></html>

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 119: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - C# Logic Conditions

Programming Logic: Execute code based on conditions.

The If ConditionC# lets you execute code based on conditions.

To test a condition you use an if statement. The if statement returns true or false, based on yourtest:

The if statement starts a code blockThe condition is written inside parenthesisThe code inside the braces is executed if the test is true

Example

@{var price=50;}<html><body>@if (price>30) { <p>The price is too high.</p> }</body></html>

Run example »

The Else ConditionAn if statement can include an else condition.

The else condition defines the code to be executed if the condition is false.

Example

@{var price=20;}<html><body>@if (price>30) { <p>The price is too high.</p> }else { <p>The price is OK.</p> } </body></html>

Run example »

Note: In the example above, if the first condition is true, it will be executed. The else condition covers"everything else".

The Else If ConditionMultiple conditions can be tested with an else if condition:

Example

@{var price=25;}<html><body>@if (price>=30) { <p>The price is high.</p> }else if (price>20 && price<30) { <p>The price is OK.</p> }else { <p>The price is low.</p> } </body></html>

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 120: ASP.Net

« Previous Next Chapter »

In the example above, if the first condition is true, it will be executed.

If not, then if the next condition is true, this condition will be executed.

You can have any number of else if conditions.

If none of the if and else if conditions are true, the last else block (without a condition) covers"everything else".

Switch ConditionsA switch block can be used to test a number of individual conditions:

Example

@{var weekday=DateTime.Now.DayOfWeek;var day=weekday.ToString();var message="";}<html><body>@switch(day){case "Monday": message="This is the first weekday."; break;case "Thursday": message="Only one day before weekend."; break;case "Friday": message="Tomorrow is weekend!"; break;default: message="Today is " + day; break;}<p>@message</p></body></html>

Run example »

The test value (day) is in parentheses. Each individual test condition has a case value that ends with acolon, and any number of code lines ending with a break statement. If the test value matches the casevalue, the code lines are executed.

A switch block can have a default case (default:) for "everything else" that runs if none of the casesare true.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 121: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - VB Variables

Variables are named entities used to store data.

VariablesVariables are used to store data.

The name of a variable must begin with an alphabetic character and cannot contain whitespace orreserved characters.

A variable can be of a specific type, indicating the kind of data it stores. String variables store stringvalues ("Welcome to W3Schools"), integer variables store number values (103), date variables storedate values, etc.

Variables are declared using the Dim keyword, or by using the type (if you want to declare the type),but ASP.NET can usually determine data types automatically.

Examples

// Using the Dim keyword:Dim greeting = "Welcome to W3Schools";Dim counter = 103;Dim today = DateTime.Today;

// Using data types:Dim greeting As String = "Welcome to W3Schools";Dim counter As Integer = 103;Dim today As DateTime = DateTime.Today;

Data TypesBelow is a list of common data types:

Type Description Examples

integer Integer (whole numbers) 103, 12, 5168

double 64 bit floating-point number 3.14, 3.4e38

decimal Decimal number (higher precision) 1037.196543

boolean Boolean true, false

string String "Hello W3Schools", "John"

OperatorsAn operator tells ASP.NET what kind of command to perform in an expression.

The VB language supports many operators. Below is a list of common operators:

Operator Description Example

= Assigns a value to a variable. i=6

+-*/

Adds a value or variable.Subtracts a value or variable.Multiplies a value or variable.Divides a value or variable.

i=5+5i=5-5i=5*5i=5/5

+=-=

Increments a variable.Decrements a variable.

i += 1i -= 1

= Equality. Returns true if values are equal. if i=10

<> Inequality. Returns true if values are not equal. if <>10

<><=>=

Less than.Greater than.Less than or equal.Greater than or equal.

if i<10if i>10if i<=10if i>=10

& Adding strings (concatenation). "w3" & "schools"

. Dot. Separate objects and methods. DateTime.Hour

() Parenthesis. Groups values. (i+5)

() Parenthesis. Passes parameters. x=Add(i,5)

() Parenthesis. Accesses values in arrays or collections. name(3)

Not Not. Reverses true or false. if Not ready

AndOR

Logical AND.Logical OR.

if ready And clearif ready Or clear

AndAlsoorElse

Extended Logical AND.Extended Logical OR.

if ready AndAlso clearif ready OrElse clear

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 122: ASP.Net

« Previous Next Chapter »

Converting Data TypesConverting from one data type to another is sometimes useful.

The most common example is to convert string input to another type, such as an integer or a date.

As a rule, user input comes as strings, even if the user entered a number. Therefore, numeric inputvalues must be converted to numbers before they can be used in calculations.

Below is a list of common conversion methods:

Method Decryptions Example

AsInt()IsInt()

Converts a string to an integer. if myString.IsInt() then myInt=myString.AsInt()end if

AsFloat()IsFloat()

Converts a string to a floating-point number. if myString.IsFloat() then myFloat=myString.AsFloat()end if

AsDecimal()IsDecimal()

Converts a string to a decimal number. if myString.IsDecimal() then myDec=myString.AsDecimal()end if

AsDateTime()IsDateTime()

Converts a string to an ASP.NET DateTime type. myString="10/10/2012"myDate=myString.AsDateTime()

AsBool()IsBool()

Converts a string to a Boolean. myString="True"myBool=myString.AsBool()

ToString() Converts any data type to a string. myInt=1234myString=myInt.ToString()

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 123: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - VB Loops and Arrays

Statements can be executed repeatedly in loops.

For LoopsIf you need to run the same statements repeatedly, you can program a loop.

If you know how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:

Example

<html><body>@For i=10 To 21 @<p>Line #@i</p>Next i</body></html>

Run example »

For Each LoopsIf you work with a collection or an array, you often use a for each loop.

A collection is a group of similar objects, and the for each loop lets you carry out a task on each item. The for each loop walks through a collection until it isfinished.

The example below walks through the ASP.NET Request.ServerVariables collection.

Example

<html><body><ul>@For Each x In Request.ServerVariables @<li>@x</li>Next x</ul></body></html>

Run example »

While LoopsThe while loop is a general purpose loop.

A while loop begins with the while keyword, followed by parentheses, where you specify how long the loop continues, then a block to repeat.

While loops typically add to, or subtract from, a variable used for counting.

In the example below, the += operator adds 1 to the variable i, each time the loop runs.

Example

<html><body>@CodeDim i=0Do While i<5 i += 1 @<p>Line #@i</p>LoopEnd Code</body></html>

Run example »

ArraysAn array is useful when you want to store similar variables but don't want to create a separate variable for each of them:

Example

@CodeDim members As String()={"Jani","Hege","Kai","Jim"}

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 124: ASP.Net

« Previous Next Chapter »

i=Array.IndexOf(members,"Kai")+1len=members.Lengthx=members(2-1)end Code<html><body><h3>Members</h3>@For Each person In members @<p>@person</p>Next person<p>The number of names in Members are @len</p><p>The person at position 2 is @x</p><p>Kai is now in position @i</p></body></html>

Run example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 125: ASP.Net

« Previous Next Chapter »

ASP.NET Razor - VB Logic Conditions

Programming Logic: Execute code based on conditions.

The If ConditionVB lets you execute code based on conditions.

To test a condition you use the if statement. The if statement returns true or false, based on yourtest:

The if statement starts a code blockThe condition is written between if and thenThe code between if ... then and end if is executed if the test is true

Example

@CodeDim price=50End Code<html><body>@If price>30 Then @<p>The price is too high.</p>End If</body></html>

Run example »

The Else ConditionAn if statement can include an else condition.

The else condition defines the code to be executed if the condition is false.

Example

@CodeDim price=20End Code<html><body>@if price>30 then @<p>The price is too high.</p>Else @<p>The price is OK.</p>End If </body></htmlV>

Run example »

Note: In the example above, if the first condition is true, it will be executed. The else condition covers"everything else".

The ElseIf ConditionMultiple conditions can be tested with an else if condition:

Example

@CodeDim price=25End Code<html><body>@If price>=30 Then @<p>The price is high.</p>ElseIf price>20 And price<30 @<p>The price is OK.</p>Else @<p>The price is low.</p>End If </body></html>

Run example »

In the example above, if the first condition is true, it will be executed.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 126: ASP.Net

« Previous Next Chapter »

If not, then if the next condition is true, this condition will be executed.

You can have any number of else if conditions.

If none of the if or else if conditions are true, the last else block (without a condition) covers"everything else".

Select ConditionsA select block can be used to test a number of individual conditions:

Example

@CodeDim weekday=DateTime.Now.DayOfWeekDim day=weekday.ToString()Dim message=""End Code<html><body>@Select Case dayCase "Monday" message="This is the first weekday."Case "Thursday" message="Only one day before weekend."Case "Friday" message="Tomorrow is weekend!"Case Else message="Today is " & dayEnd Select<p>@message</p></body></html>

Run example »

"Select Case" is followed by the test value (day). Each individual test condition has a case value, andany number of code lines. If the test value matches the case value, the code lines are executed.

A select block can have a default case (Case Else) for "everything else" that runs if none of the othercases are true.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 127: ASP.Net

« Previous Next Chapter »

ASP.NET MVC Tutorial

ASP.NET is a development framework for building web pages andweb sites with HTML, CSS, JavaScript and server scripting.

ASP.NET supports three different development models:Web Pages, MVC (Model View Controller), and Web Forms.

THIS TUTORIAL COVERS MVC

Web Pages MVC Web Forms

ASP.NET Framework

The MVC Programming ModelMVC is one of three ASP.NET programming models.

MVC is a framework for building web applications using a MVC (Model View Controller) design:

The Model represents the application core (for instance a list of database records).The View displays the data (the database records).The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.

The MVC model defines web applications with 3 logic layers:

The business layer (Model logic)

The display layer (View logic)

The input control (Controller logic)

The Model is the part of the application that handles the logic for the application data.Often model objects retrieve data (and store data) from a database.

The View is the parts of the application that handles the display of the data.Most often the views are created from the model data.

The Controller is the part of the application that handles user interaction.Typically controllers read data from a view, control user input, and send input data to the model.

The MVC separation helps you manage complex applications, because you can focus on one aspect atime. For example, you can focus on the view without depending on the business logic. It also makes iteasier to test an application.

The MVC separation also simplifies group development. Different developers can work on the view, thecontroller logic, and the business logic in parallel.

Web Forms vs MVCThe MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is alightweight, highly testable framework, integrated with all existing ASP.NET features, such as MasterPages, Security, and Authentication.

Visual Web DeveloperVisual Web Developer is the free version of Microsoft Visual Studio.

Visual Web Developer is a development tool tailor made for MVC (and Web Forms).

Visual Web Developer contains:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 128: ASP.Net

« Previous Next Chapter »

MVC and Web FormsDrag-and-drop web controls and web componentsA web server language (Razor using VB or C#)A web server (IIS Express)A database server (SQL Server Compact)A full web development framework (ASP.NET)

If you install Visual Web Developer, you will get more benefits from this tutorial.

If you want to install Visual Web Developer, click on this link:

http://www.microsoft.com/web/gallery/install.aspx?appid=VWDorVS2010SP1Pack

After you have installed Visual Web Developer the first time, it pays to run the installation onemore time, to install fixes and service packs.Just click on the link once more.

ASP.NET MVC ReferencesAt the end of this tutorial you will find a complete ASP.NET MVC reference.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 129: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Internet Application

To learn ASP.NET MVC, we will Build an Internet Application

Part I: Creating the Application

What We Will BuildWe will build an Internet application that supports adding, editing, deleting, and listing of information stored in a database.

What We Will DoVisual Web Developer offers different templates for building web applications.

We will use Visual Web Developer to create an empty MVC Internet application with HTML5 markup.

When the empty Internet application is created, we will gradually add code to the application until it is fully finished. We will use C# as the programminglanguage, and the newest Razor server code markup.

Along the way we will explain the content, the code, and all the components of the application.

Creating the Web ApplicationIf you have Visual Web Developer installed, start Visual Web Developer and select New Project. Otherwise just read and learn.

In the New Project dialog box:

Open the Visual C# templatesSelect the template ASP.NET MVC 3 Web ApplicationSet the project name to MvcDemoSet the disk location to something like c:\w3schools_demoClick OK

When the New Project Dialog Box opens:

Select the Internet Application templateSelect the Razor EngineSelect HTML5 MarkupClick OK

Visual Studio Express will create a project much like this:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 130: ASP.Net

« Previous Next Chapter »

We will explore the content of the files and folders in the next chapter of this tutorial.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 131: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Application Folders

To learn ASP.NET MVC, we are Building an Internet application

Part II: Exploring the Application Folders

MVC FoldersA typical ASP.NET MVC web application has the following folder content:

Application information

PropertiesReferences

Application folders

App_Data FolderContent Folder

Controllers FolderModels FolderScripts FolderViews Folder

Configuration files

Global.asaxpackages.config

Web.config

The folder names are equal in all MVC applications. The MVC framework is based on default naming. Controllers are in the Controllers folder, Views are in theViews folder, and Models are in the Models folder. You don't have to use the folder names in your application code.

Standard naming reduces the amount of code, and makes it easier for developers to understand MVC projects.

Below is a brief summary of the content of each folder:

The App_Data FolderThe App_Data folder is for storing application data.

We will add an SQL database to the App_Data folder, later in this tutorial.

The Content FolderThe Content folder is used for static files like style sheets (css files), icons and images.

Visual Web Developer automatically adds a themes folder to the Content folder. The themes folder is filled with jQuery styles and pictures. In this projectyou can delete the themes folder.

Visual Web Developer also adds a standard style sheet file to the project: the file Site.css in the content folder. The style sheet file is the file to edit whenyou want to change the style of the application.

We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.

The Controllers FolderThe Controllers folder contains the controller classes responsible for handling user input and responses.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 132: ASP.Net

MVC requires the name of all controller files to end with "Controller".

Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):

We will create more controllers later in this tutorial.

The Models FolderThe Models folder contains the classes that represent the application models. Models hold and manipulate application data.

We will create models (classes) in a later chapter of this tutorial.

The Views FolderThe Views folder stores the HTML files related to the display of the application (the user interfaces).

The Views folder contains one folder for each controller.

Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside the Views folder).

The Account folder contains pages for registering and logging in to user accounts.

The Home folder is used for storing application pages like the home page and the about page.

The Shared folder is used to store views shared between controllers (master pages and layout pages).

We will edit the layout files in the next chapter of this tutorial.

The Scripts FolderThe Scripts folder stores the JavaScript files of the application.

By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 133: ASP.Net

« Previous Next Chapter »

Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 134: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Styles and Layout

To learn ASP.NET MVC, we are Building an Internet Application.

Part III: Adding Styles and a Consistent Look (Layout).

Adding a LayoutThe file _Layout.cshtml represent the layout of each page in the application. It is located in the Shared folder inside the Views folder.

Open the file and swap the content with this:

<!DOCTYPE html><html><head><meta charset="utf-8" /><title>@ViewBag.Title</title><link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"type="text/css" /><script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"type="text/javascript"></script><script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"type="text/javascript"></script></head><body><ul id="menu"><li>@Html.ActionLink("Home", "Index", "Home")</li><li>@Html.ActionLink("Movies", "Index", "Movies")</li><li>@Html.ActionLink("About", "About", "Home")</li></ul> <section id="main">@RenderBody()<p>Copyright W3schools 2012. All Rights Reserved.</p></section></body></html>

HTML HelpersIn the code above, HTML helpers are used to modify HTML output:

@Url.Content() - URL content will be inserted here.

@Html.ActionLink() - HTML link will be inserted here.

You will learn more about HTML helpers in a later chapter of this tutorial.

Razor SyntaxIn the code above, the code marked red are C# using Razor markup.

@ViewBag.Title - The page title will be inserted here.

@RenderBody() - The page content will be rendered here.

You can learn about Razor markup for both C# and VB (Visual Basic) in our Razor tutorial.

Adding StylesThe style sheet for the application is called Site.css. It is located in the Content folder.

Open the file Site.css and swap the content with this:

body{font: "Trebuchet MS", Verdana, sans-serif;background-color: #5c87b2;color: #696969;}h1{border-bottom: 3px solid #cc9900;font: Georgia, serif;color: #996600;}#main{padding: 20px;background-color: #ffffff;border-radius: 0 4px 4px 4px;}a{color: #034af3; }/* Menu Styles ------------------------------*/ ul#menu{padding: 0px;

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 135: ASP.Net

« Previous Next Chapter »

position: relative;margin: 0;}ul#menu li{display: inline;}ul#menu li a {background-color: #e8eef4;padding: 10px 20px;text-decoration: none;line-height: 2.8em;/*CSS3 properties*/border-radius: 4px 4px 0 0;}ul#menu li a:hover{background-color: #ffffff;} /* Forms Styles ------------------------------*/ fieldset{padding-left: 12px;} fieldset label{display: block;padding: 4px;}input[type="text"], input[type="password"]{width: 300px;}input[type="submit"]{padding: 4px;}/* Data Styles ------------------------------*/ table.data{background-color:#ffffff;border:1px solid #c3c3c3;border-collapse:collapse;width:100%;}table.data th{background-color:#e8eef4;border:1px solid #c3c3c3;padding:3px;}table.data td {border:1px solid #c3c3c3;padding:3px;}

The _View_Start FileThe _View_Start file in the Shared folder (inside the Views folder) contains the following content:

@{Layout = "~/Views/Shared/_Layout.cshtml";}

This code is automatically added to all views displayed by the application.

If you remove this file, you must add this line to all views.

You will learn more about views in a later chapter of this tutorial.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 136: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET MVC - Controllers

To learn ASP.NET MVC, we are Building an Internet Application.

Part IV: Adding a Controller.

The Controllers FolderThe Controllers Folder contains the controller classes responsible for handling user input and responses.

MVC requires the name of all controllers to end with "Controller".

In our example, Visual Web Developer has created the following files: HomeController.cs (for the Home and About pages) and AccountController.cs (Forthe Log On pages):

Web servers will normally map incoming URL requests directly to disk files on the server. For example: an URL request like"http://www.w3schools.com/default.asp" will map directly to the file "default.asp" at the root directory of the server.

The MVC framework maps differently. MVC maps URLs to methods. These methods are in classes called "Controllers".

Controllers are responsible for processing incoming requests, handling input, saving data, and sending a response to send back to the client.

The Home controllerThe controller file in our application HomeController.cs, defines the two controls Index and About.

Swap the content of the HomeController.cs file with this:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;

namespace MvcDemo.Controllers{public class HomeController : Controller{public ActionResult Index(){return View();}

public ActionResult About(){return View();}}}

The Controller ViewsThe files Index.cshtml and About.cshtml in the Views folder defines the ActionResult views Index() and About() in the controller.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 137: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Views

To learn ASP.NET MVC, we are Building an Internet Application.

Part V: Adding Views for Displaying the Application.

The Views FolderThe Views folder stores the files (HTML files) related to the display of the application (the userinterfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending onthe language content.

The Views folder contains one folder for each controller.

Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside theViews folder).

The Account folder contains pages for registering and logging in to user accounts.

The Home folder is used for storing application pages like the home page and the about page.

The Shared folder is used to store views shared between controllers (master pages and layout pages).

ASP.NET File TypesThe following HTML file types can be found in the Views Folder:

File Type Extention

Plain HTML .htm or .html

Classic ASP .asp

Classic ASP.NET .aspx

ASP.NET Razor C# .cshtml

ASP.NET Razor VB .vbhtml

The Index FileThe file Index.cshtml represents the Home page of the application. It is the application's default file(index file).

Put the following content in the file:

@{ViewBag.Title = "Home Page";}

<h1>Welcome to W3Schools</h1>

<p>Put Home Page content here</p>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 138: ASP.Net

« Previous Next Chapter »

The About FileThe file About.cshtml represent the About page of the application.

Put the following content in the file:

@{ViewBag.Title = "About Us";}

<h1>About Us</h1>

<p>Put About Us content here</p>

Run the ApplicationSelect Debug, Start Debugging (or F5) from the Visual Web Developer menu.

Your application will look like this:

Click on the "Home" tab and the "About" tab to see how it works.

CongratulationsCongratulations. You have created your first MVC Application.

Note: You cannot click on the "Movies" tab yet. We will add code for the "Movies" tab in the nextchapters of this tutorial.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 139: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - SQL Database

To learn ASP.NET MVC, we are Building an Internet Application.

Part VI: Adding a Database.

Creating the DatabaseVisual Web Developer comes with a free SQL database called SQL Server Compact.

The database needed for this tutorial can be created with these simple steps:

Right-click the App_Data folder in the Solution Explorer windowSelect Add, New ItemSelect SQL Server Compact Local Database *Name the database Movies.sdf.Click the Add button

* If SQL Server Compact Local Database is not an option, you have not installed SQL Server Compact on your computer. Install it from this link: SQL ServerCompact

Visual Web Developer automatically creates the database in the App_Data folder.

Note: In this tutorial it is expected that you have some knowledge about SQL databases. If you want to study this topic first, please visit our SQL Tutorial.

Adding a Database TableDouble-clicking the Movies.sdf file in the App_Data folder will open a Database Explorer window.

To create a new table in the database, right-click the Tables folder, and select Create Table.

Create the following columns:

Column Type Allow Nulls

ID int (primary key) No

Title nvarchar(100) No

Director nvarchar(100) No

Date datetime No

Columns explained:

ID is an integer (whole number) used to identify each record in the table.

Title is a 100 character text column to store the name of the movie.

Director is a 100 character text column to store the director's name.

Date is a datetime column to store the release date of the movie.

After creating the columns described above, you must make the ID column the table's primary key (record identifier). To do this, click on the column name(ID) and select Primary Key. Also, in the Column Properties window, set the Identity property to True:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 140: ASP.Net

« Previous Next Chapter »

When you have finished creating the table columns, save the table and name it MovieDBs.

Note:

We have deliberately named the table "MovieDBs" (ending with s). In the next chapter, you will see the name "MovieDB" used for the data model. It looksstrange, but this is the naming convention you have to use to make the controller connect to the database table.

Adding Database RecordsYou can use Visual Web Developer to add some test records to the movie database.

Double-click the Movies.sdf file in the App_Data folder.

Right-click the MovieDBs table in the Database Explorer window and select Show Table Data.

Add some records:

ID Title Director Date

1 Psycho Alfred Hitchcock 01.01.1960

2 La Dolce Vita Federico Fellini 01.01.1960

Note: The ID column is updated automatically. You should not edit it.

Adding a Connection StringAdd the following element to the <connectionStrings> element in your Web.config file:

<add name="MovieDBContext"connectionString="Data Source=|DataDirectory|Movies.sdf"providerName="System.Data.SqlServerCe.4.0"/>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 141: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Models

To learn ASP.NET MVC, we are Building an Internet Application.

Part VII: Adding a Data Model.

MVC ModelsThe MVC Model contains all application logic (business logic, validation logic, and data access logic), except pure view and controller logic.

With MVC, models both hold and manipulate application data.

The Models FolderThe Models Folder contains the classes that represent the application model.

Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application security.

AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel.

Adding a Database ModelThe database model needed for this tutorial can be created with these simple steps:

In the Solution Explorer, right-click the Models folder, and select Add and Class.Name the class MovieDB.cs, and click Add.Edit the class:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;

namespace MvcDemo.Models{public class MovieDB{public int ID { get; set; }public string Title { get; set; }public string Director { get; set; }public DateTime Date { get; set; }

}public class MovieDBContext : DbContext{public DbSet<MovieDB> Movies { get; set; } }}

Note:

We have deliberately named the model class "MovieDB". In the previous chapter, you saw the name "MovieDBs" (endig with s) used for the database table.It looks strange, but this is the naming convention you have to use to make the model connect to the database table.

Adding a Database ControllerThe database controller needed for this tutorial can be created with these simple steps:

In the Solution Explorer, right-click the Controllers folder, and select Add and ControllerSet controller name to MoviesControllerSelect template: Controller with read/write actions and views, using Entity FrameworkSelect model class: MovieDB (McvDemo.Models)Select data context class: MovieDBContext (McvDemo.Models)Select views Razor (CSHTML)Click Add

Visual Web Developer will create the following files:

A MoviesController.cs file in the Controllers folderA Movies folder in the Views folder

Adding Database ViewsThe following files are automatically created in the Movies folder:

Create.cshtmlDelete.cshtmlDetails.cshtmlEdit.cshtmlIndex.cshtml

Congratulations

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 142: ASP.Net

« Previous Next Chapter »

Congratulations. You have added your first MVC data model to your application.

Now you can click on the "Movies" tab :-)

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 143: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Security

To learn ASP.NET MVC, we are Building an Internet Application.

Part VIII: Adding Security.

MVC Application SecurityThe Models Folder contains the classes that represent the application model.

Visual Web Developer automatically creates an AccountModels.cs file that contains the models forapplication authentication.

AccountModels contains a LogOnModel, a ChangePasswordModel, and a RegisterModel:

The Change Password Model

public class ChangePasswordModel{

[Required][DataType(DataType.Password)][Display(Name = "Current password")]public string OldPassword { get; set; }

[Required][StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)][DataType(DataType.Password)][Display(Name = "New password")]public string NewPassword { get; set; }

[DataType(DataType.Password)][Display(Name = "Confirm new password")][Compare("NewPassword", ErrorMessage = "The new password and confirmationpassword do not match.")]public string ConfirmPassword { get; set; }

}

The Logon Model

public class LogOnModel{

[Required][Display(Name = "User name")]public string UserName { get; set; }

[Required][DataType(DataType.Password)][Display(Name = "Password")]public string Password { get; set; }

[Display(Name = "Remember me?")]public bool RememberMe { get; set; }

}

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 144: ASP.Net

« Previous Next Chapter »

The Register Model

public class RegisterModel{

[Required][Display(Name = "User name")]public string UserName { get; set; }

[Required][DataType(DataType.EmailAddress)][Display(Name = "Email address")]public string Email { get; set; }

[Required][StringLength(100, ErrorMessage = "The {0} must be at least {2} characterslong.", MinimumLength = 6)][DataType(DataType.Password)][Display(Name = "Password")]public string Password { get; set; }

[DataType(DataType.Password)][Display(Name = "Confirm password")][Compare("Password", ErrorMessage = "The password and confirmation passworddo not match.")]public string ConfirmPassword { get; set; }

}

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 145: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - HTML Helpers

HTML Helpers are used to modify HTML output

HTML HelpersWith MVC, HTML helpers are much like traditional ASP.NET Web Form controls.

Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTMLhelper does not have an event model and a view state.

In most cases, an HTML helper is just a method that returns a string.

With MVC, you can create your own helpers, or use the built in HTML helpers.

Standard HTML HelpersMVC includes standard helpers for the most common types of HTML elements, like HTML links and HTML form elements.

HTML LinksThe easiest way to render an HTML link in is to use the HTML.ActionLink() helper.

With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.

Razor Syntax:

@Html.ActionLink("About this Website", "About")

ASP Syntax:

<%=Html.ActionLink("About this Website", "About")%>

The first parameter is the link text, and the second parameter is the name of the controller action.

The Html.ActionLink() helper above, outputs the following HTML:

<a href="/Home/About">About this Website</a>

The Html.ActionLink() helper as several properties:

Property Description

.linkText The link text (label)

.actionName The target action

.routeValues The values passed to the action

.controllerName The target controller

.htmlAttributes The set of attributes to the link

.protocol The link protocol

.hostname The host name for the link

.fragment The anchor target for the link

Note: You can pass values to a controller action. For example, you can pass the id of a database record to a database edit action:

Razor Syntax C#:

@Html.ActionLink("Edit Record", "Edit", new {Id=3})

Razor Syntax VB:

@Html.ActionLink("Edit Record", "Edit", New With{.Id=3})

The Html.ActionLink() helper above, outputs the following HTML:

<a href="/Home/Edit/3">Edit Record</a>

HTML Form ElementsThere following HTML helpers can be used to render (modify and output) HTML form elements:

BeginForm()EndForm()TextArea()TextBox()CheckBox()

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 146: ASP.Net

« Previous Next Chapter »

RadioButton()ListBox()DropDownList()Hidden()Password()

ASP.NET Syntax C#:

<%= Html.ValidationSummary("Create was unsuccessful. Please correct theerrors and try again.") %><% using (Html.BeginForm()){%><p><label for="FirstName">First Name:</label><%= Html.TextBox("FirstName") %><%= Html.ValidationMessage("FirstName", "*") %></p><p><label for="LastName">Last Name:</label><%= Html.TextBox("LastName") %><%= Html.ValidationMessage("LastName", "*") %></p><p><label for="Password">Password:</label><%= Html.Password("Password") %><%= Html.ValidationMessage("Password", "*") %></p><p><label for="Password">Confirm Password:</label><%= Html.Password("ConfirmPassword") %><%= Html.ValidationMessage("ConfirmPassword", "*") %></p><p><label for="Profile">Profile:</label><%= Html.TextArea("Profile", new {cols=60, rows=10})%></p><p><%= Html.CheckBox("ReceiveNewsletter") %><label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label></p><p><input type="submit" value="Register" /></p><%}%>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 147: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Publishing the Website

Learn how to publish an MVC application without using Visual Web Developer.

Publish Your Application Without Using Visual Web DeveloperAn ASP.NET MVC application can be published to a remote server by using the Publish commands in WebMatrix ,Visual Web Developer, or Visual Studio.

This function copies all your application files, controllers, models, images, and all the required DLL files for MVC, Web Pages, Razor, Helpers, and SQL ServerCompact (if a database is used).

Sometimes you don't want to use this option. Maybe your hosting provider only supports FTP? Maybe you already have a web site based on classic ASP?Maybe you want to copy the files yourself? Maybe you want to use Front Page, Expression Web, or some other publishing software?

Will you get a problem? Yes, you will. But you can solve it.

To perform a web copy, you have to know how to include the right files, what DDL files to copy, and where store them.

Follow these steps:

1. Use the Latest Version of ASP.NETBefore you continue, make sure your hosting computer runs the latest version of ASP.NET (4.0).

2. Copy the Web FoldersCopy your website (all folders and content) from your development computer to an application folder on your remote hosting computer (server).

If your App_Data folder contains test data, don't copy the App_Data folder (see SQL Data below).

3. Copy the DLL FilesOn the remote server create a bin folder in the root of your application. (If you have installed Helpers, you already have a bin folder)

Copy everything from your folders:

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies

to your application's bin folder on the remote server.

4. Copy the SQL Server Compact DLL FilesIf your application has a SQL Server Compact database (an .sdf file in App_Data folder), you must copy the SQL Server Compact DLL files:

Copy everything from your folder:

C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Private

to your application's bin folder on the remote server.

Create (or edit) the Web.config file for your application:

Example C#

<?xml version="1.0" encoding="UTF-8"?><configuration><system.data><DbProviderFactories><remove invariant="System.Data.SqlServerCe.4.0" />

<add invariant="System.Data.SqlServerCe.4.0"name="Microsoft SQL Server Compact 4.0"description=".NET Framework Data Provider for Microsoft SQL Server Compact"type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe,Version=4.0.0.1,Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

</DbProviderFactories></system.data></configuration>

5. Copy SQL Server Compact DataDo you have .sdf files in your App_Data folder that contains test data?

Do you want to publish the test data to the remote server?

Most likely not.

If you have to copy the SQL data files (.sdf files), you should delete everything in the database, and then copy the empty .sdf file from your developmentcomputer to the server.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 148: ASP.Net

« Previous Next Chapter »

THAT'S IT. GOOD LUCK !

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 149: ASP.Net

« Previous Next Chapter »

ASP.NET MVC - Reference

Classes

Class Description

AcceptVerbsAttribute Represents an attribute that specifies which HTTP verbs anaction method will respond to.

ActionDescriptor Provides information about an action method, such as itsname, controller, parameters, attributes, and filters.

ActionExecutedContext Provides the context for the ActionExecuted method of theActionFilterAttribute class.

ActionExecutingContext Provides the context for the ActionExecuting method of theActionFilterAttribute class.

ActionFilterAttribute Represents the base class for filter attributes.

ActionMethodSelectorAttribute Represents an attribute that is used to influence the selectionof an action method.

ActionNameAttribute Represents an attribute that is used for the name of anaction.

ActionNameSelectorAttribute Represents an attribute that affects the selection of an actionmethod.

ActionResult Encapsulates the result of an action method and is used toperform a framework-level operation on behalf of the actionmethod.

AdditionalMetadataAttribute Provides a class that implements the IMetadataAwareinterface in order to support additional metadata.

AjaxHelper Represents support for rendering HTML in AJAX scenarioswithin a view.

AjaxHelper(Of TModel) Represents support for rendering HTML in AJAX scenarioswithin a strongly typed view.

AjaxRequestExtensions Represents a class that extends the HttpRequestBase classby adding the ability to determine whether an HTTP requestis an AJAX request.

AllowHtmlAttribute Allows a request to include HTML markup during modelbinding by skipping request validation for the property. (It isstrongly recommended that your application explicitly checkall models where you disable request validation in order toprevent script exploits.)

AreaRegistration Provides a way to register one or more areas in an ASP.NETMVC application.

AreaRegistrationContext Encapsulates the information that is required in order toregister an area within an ASP.NET MVC application.

AssociatedMetadataProvider Provides an abstract class to implement a metadata provider.

AssociatedValidatorProvider Provides an abstract class for classes that implement avalidation provider.

AsyncController Provides the base class for asynchronous controllers.

AsyncTimeoutAttribute Represents an attribute that is used to set the timeout value,in milliseconds, for an asynchronous method.

AuthorizationContext Encapsulates the information that is required for using anAuthorizeAttribute attribute.

AuthorizeAttribute Represents an attribute that is used to restrict access bycallers to an action method.

BindAttribute Represents an attribute that is used to provide details abouthow model binding to a parameter should occur.

BuildManagerCompiledView Represents the base class for views that are compiled by theBuildManager class before being rendered by a view engine.

BuildManagerViewEngine Provides a base class for view engines.

ByteArrayModelBinder Maps a browser request to a byte array.

ChildActionOnlyAttribute Represents an attribute that is used to indicate that an actionmethod should be called only as a child action.

ChildActionValueProvider Represents a value provider for values from child actions.

ChildActionValueProviderFactory Represents a factory for creating value provider objects forchild actions.

ClientDataTypeModelValidatorProvider Returns the client data-type model validators.

CompareAttribute Provides an attribute that compares two properties of amodel.

ContentResult Represents a user-defined content type that is the result ofan action method.

Controller Provides methods that respond to HTTP requests that aremade to an ASP.NET MVC Web site.

ControllerActionInvoker Represents a class that is responsible for invoking the action

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 150: ASP.Net

methods of a controller.

ControllerBase Represents the base class for all MVC controllers.

ControllerBuilder Represents a class that is responsible for dynamicallybuilding a controller.

ControllerContext Encapsulates information about an HTTP request thatmatches specified RouteBase and ControllerBase instances.

ControllerDescriptor Encapsulates information that describes a controller, such asits name, type, and actions.

ControllerInstanceFilterProvider Adds the controller to the FilterProviderCollection instance.

CustomModelBinderAttribute Represents an attribute that invokes a custom model binder.

DataAnnotationsModelMetadata Provides a container for common metadata, for theDataAnnotationsModelMetadataProvider class, and for theDataAnnotationsModelValidator class for a data model.

DataAnnotationsModelMetadataProvider Implements the default model metadata provider forASP.NET MVC.

DataAnnotationsModelValidator Provides a model validator.

DataAnnotationsModelValidator(OfTAttribute)

Provides a model validator for a specified validation type.

DataAnnotationsModelValidatorProvider Implements the default validation provider for ASP.NET MVC.

DataErrorInfoModelValidatorProvider Provides a container for the error-information modelvalidator.

DefaultControllerFactory Represents the controller factory that is registered bydefault.

DefaultModelBinder Maps a browser request to a data object. This class providesa concrete implementation of a model binder.

DefaultViewLocationCache Represents a memory cache for view locations.

DependencyResolver Provides a registration point for dependency resolvers thatimplement IDependencyResolver or the Common ServiceLocator IServiceLocator interface.

DependencyResolverExtensions Provides a type-safe implementation of GetService andGetServices.

DictionaryValueProvider(Of TValue) Represents the base class for value providers whose valuescome from a collection that implements the IDictionary(OfTKey, TValue) interface.

EmptyModelMetadataProvider Provides an empty metadata provider for data models thatdo not require metadata.

EmptyModelValidatorProvider Provides an empty validation provider for models that do notrequire a validator.

EmptyResult Represents a result that does nothing, such as a controlleraction method that returns nothing.

ExceptionContext Provides the context for using the HandleErrorAttribute class.

ExpressionHelper Provides a helper class to get the model name from anexpression.

FieldValidationMetadata Provides a container for client-side field validation metadata.

FileContentResult Sends the contents of a binary file to the response.

FilePathResult Sends the contents of a file to the response.

FileResult Represents a base class that is used to send binary filecontent to the response.

FileStreamResult Sends binary content to the response by using a Streaminstance.

Filter Represents a metadata class that contains a reference to theimplementation of one or more of the filter interfaces, thefilter's order, and the filter's scope.

FilterAttribute Represents the base class for action and result filterattributes.

FilterAttributeFilterProvider Defines a filter provider for filter attributes.

FilterInfo Encapsulates information about the available action filters.

FilterProviderCollection Represents the collection of filter providers for theapplication.

FilterProviders Provides a registration point for filters.

FormCollection Contains the form value providers for the application.

FormContext Encapsulates information that is required in order to validateand process the input data from an HTML form.

FormValueProvider Represents a value provider for form values that arecontained in a NameValueCollection object.

FormValueProviderFactory Represents a class that is responsible for creating a newinstance of a form-value provider object.

GlobalFilterCollection Represents a class that contains all the global filters.

GlobalFilters Represents the global filter collection.

HandleErrorAttribute Represents an attribute that is used to handle an exceptionthat is thrown by an action method.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 151: ASP.Net

HandleErrorInfo Encapsulates information for handling an error that wasthrown by an action method.

HiddenInputAttribute Represents an attribute that is used to indicate whether aproperty or field value should be rendered as a hidden inputelement.

HtmlHelper Represents support for rendering HTML controls in a view.

HtmlHelper(Of TModel) Represents support for rendering HTML controls in a stronglytyped view.

HttpDeleteAttribute Represents an attribute that is used to restrict an actionmethod so that the method handles only HTTP DELETErequests.

HttpFileCollectionValueProvider Represents a value provider to use with values that comefrom a collection of HTTP files.

HttpFileCollectionValueProviderFactory Represents a class that is responsible for creating a newinstance of an HTTP file collection value provider object.

HttpGetAttribute Represents an attribute that is used to restrict an actionmethod so that the method handles only HTTP GET requests.

HttpNotFoundResult Defines an object that is used to indicate that the requestedresource was not found.

HttpPostAttribute Represents an attribute that is used to restrict an actionmethod so that the method handles only HTTP POSTrequests.

HttpPostedFileBaseModelBinder Binds a model to a posted file.

HttpPutAttribute Represents an attribute that is used to restrict an actionmethod so that the method handles only HTTP PUT requests.

HttpRequestExtensions Extends the HttpRequestBase class that contains the HTTPvalues that were sent by a client during a Web request.

HttpStatusCodeResult Provides a way to return an action result with a specific HTTPresponse status code and description.

HttpUnauthorizedResult Represents the result of an unauthorized HTTP request.

JavaScriptResult Sends JavaScript content to the response.

JsonResult Represents a class that is used to send JSON-formattedcontent to the response.

JsonValueProviderFactory Enables action methods to send and receive JSON-formattedtext and to model-bind the JSON text to parameters ofaction methods.

LinqBinaryModelBinder Maps a browser request to a LINQ Binary object.

ModelBinderAttribute Represents an attribute that is used to associate a modeltype to a model-builder type.

ModelBinderDictionary Represents a class that contains all model binders for theapplication, listed by binder type.

ModelBinderProviderCollection Provides a container for model binder providers.

ModelBinderProviders Provides a container for model binder providers.

ModelBinders Provides global access to the model binders for theapplication.

ModelBindingContext Provides the context in which a model binder functions.

ModelClientValidationEqualToRule Provides a container for an equality validation rule that issent to the browser.

ModelClientValidationRangeRule Provides a container for a range-validation rule that is sentto the browser.

ModelClientValidationRegexRule Provides a container for a regular-expression client validationrule that is sent to the browser.

ModelClientValidationRemoteRule Provides a container for a remote validation rule that is sentto the browser.

ModelClientValidationRequiredRule Provides a container for client validation for required field.

ModelClientValidationRule Provides a base class container for a client validation rulethat is sent to the browser.

ModelClientValidationStringLengthRule Provides a container for a string-length validation rule that issent to the browser.

ModelError Represents an error that occurs during model binding.

ModelErrorCollection A collection of ModelError instances.

ModelMetadata Provides a container for common metadata, for theModelMetadataProvider class, and for the ModelValidatorclass for a data model.

ModelMetadataProvider Provides an abstract base class for a custom metadataprovider.

ModelMetadataProviders Provides a container for the current ModelMetadataProviderinstance.

ModelState Encapsulates the state of model binding to a property of anaction-method argument, or to the argument itself.

ModelStateDictionary Represents the state of an attempt to bind a posted form toan action method, which includes validation information.

ModelValidationResult Provides a container for a validation result.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 152: ASP.Net

ModelValidator Provides a base class for implementing validation logic.

ModelValidatorProvider Provides a list of validators for a model.

ModelValidatorProviderCollection Provides a container for a list of validation providers.

ModelValidatorProviders Provides a container for the current validation provider.

MultiSelectList Represents a list of items that users can select more thanone item from.

MvcFilter When implemented in a derived class, provides a metadataclass that contains a reference to the implementation of oneor more of the filter interfaces, the filter's order, and thefilter's scope.

MvcHandler Selects the controller that will handle an HTTP request.

MvcHtmlString Represents an HTML-encoded string that should not beencoded again.

MvcHttpHandler Verifies and processes an HTTP request.

MvcRouteHandler Creates an object that implements the IHttpHandler interfaceand passes the request context to it.

MvcWebRazorHostFactory Creates instances of MvcWebPageRazorHost files.

NameValueCollectionExtensions Extends a NameValueCollection object so that the collectioncan be copied to a specified dictionary.

NameValueCollectionValueProvider Represents the base class for value providers whose valuescome from a NameValueCollection object.

NoAsyncTimeoutAttribute Provides a convenience wrapper for theAsyncTimeoutAttribute attribute.

NonActionAttribute Represents an attribute that is used to indicate that acontroller method is not an action method.

OutputCacheAttribute Represents an attribute that is used to mark an actionmethod whose output will be cached.

ParameterBindingInfo Encapsulates information for binding action-methodparameters to a data model.

ParameterDescriptor Contains information that describes a parameter.

PartialViewResult Represents a base class that is used to send a partial view tothe response.

PreApplicationStartCode Provides a registration point for ASP.NET Razor pre-application start code.

QueryStringValueProvider Represents a value provider for query strings that arecontained in a NameValueCollection object.

QueryStringValueProviderFactory Represents a class that is responsible for creating a newinstance of a query-string value-provider object.

RangeAttributeAdapter Provides an adapter for the RangeAttribute attribute.

RazorView Represents the class used to create views that have Razorsyntax.

RazorViewEngine Represents a view engine that is used to render a Web pagethat uses the ASP.NET Razor syntax.

RedirectResult Controls the processing of application actions by redirectingto a specified URI.

RedirectToRouteResult Represents a result that performs a redirection by using thespecified route values dictionary.

ReflectedActionDescriptor Contains information that describes a reflected actionmethod.

ReflectedControllerDescriptor Contains information that describes a reflected controller.

ReflectedParameterDescriptor Contains information that describes a reflected action-method parameter.

RegularExpressionAttributeAdapter Provides an adapter for the RegularExpressionAttributeattribute.

RemoteAttribute Provides an attribute that uses the jQuery validation plug-inremote validator.

RequiredAttributeAdapter Provides an adapter for the RequiredAttributeAttributeattribute.

RequireHttpsAttribute Represents an attribute that forces an unsecured HTTPrequest to be re-sent over HTTPS.

ResultExecutedContext Provides the context for the OnResultExecuted method of theActionFilterAttribute class.

ResultExecutingContext Provides the context for the OnResultExecuting method of theActionFilterAttribute class.

RouteCollectionExtensions Extends a RouteCollection object for MVC routing.

RouteDataValueProvider Represents a value provider for route data that is containedin an object that implements the IDictionary(Of TKey,TValue) interface.

RouteDataValueProviderFactory Represents a factory for creating route-data value providerobjects.

SelectList Represents a list that lets users select one item.

SelectListItem Represents the selected item in an instance of the SelectList

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 153: ASP.Net

class.

SessionStateAttribute Specifies the session state of the controller.

SessionStateTempDataProvider Provides session-state data to the currentTempDataDictionary object.

StringLengthAttributeAdapter Provides an adapter for the StringLengthAttribute attribute.

TempDataDictionary Represents a set of data that persists only from one requestto the next.

TemplateInfo Encapsulates information about the current template context.

UrlHelper Contains methods to build URLs for ASP.NET MVC within anapplication.

UrlParameter Represents an optional parameter that is used by theMvcHandler class during routing.

ValidatableObjectAdapter Provides an object adapter that can be validated.

ValidateAntiForgeryTokenAttribute Represents an attribute that is used to prevent forgery of arequest.

ValidateInputAttribute Represents an attribute that is used to mark action methodswhose input must be validated.

ValueProviderCollection Represents the collection of value-provider objects for theapplication.

ValueProviderDictionary Obsolete. Represents a dictionary of value providers for theapplication.

ValueProviderFactories Represents a container for value-provider factory objects.

ValueProviderFactory Represents a factory for creating value-provider objects.

ValueProviderFactoryCollection Represents the collection of value-provider factories for theapplication.

ValueProviderResult Represents the result of binding a value (such as from aform post or query string) to an action-method argumentproperty, or to the argument itself.

ViewContext Encapsulates information that is related to rendering a view.

ViewDataDictionary Represents a container that is used to pass data between acontroller and a view.

ViewDataDictionary(Of TModel) Represents a container that is used to pass strongly typeddata between a controller and a view.

ViewDataInfo Encapsulates information about the current template contentthat is used to develop templates and about HTML helpersthat interact with templates.

ViewEngineCollection Represents a collection of view engines that are available tothe application.

ViewEngineResult Represents the result of locating a view engine.

ViewEngines Represents a collection of view engines that are available tothe application.

ViewMasterPage Represents the information that is needed to build a masterview page.

ViewMasterPage(Of TModel) Represents the information that is required in order to builda strongly typed master view page.

ViewPage Represents the properties and methods that are needed torender a view as a Web Forms page.

ViewPage(Of TModel) Represents the information that is required in order to rendera strongly typed view as a Web Forms page.

ViewResult Represents a class that is used to render a view by using anIView instance that is returned by an IViewEngine object.

ViewResultBase Represents a base class that is used to provide the model tothe view and then render the view to the response.

ViewStartPage Provides an abstract class that can be used to implement aview start (master) page.

ViewTemplateUserControl Provides a container for TemplateInfo objects.

ViewTemplateUserControl(Of TModel) Provides a container for TemplateInfo objects.

ViewType Represents the type of a view.

ViewUserControl Represents the information that is needed to build a usercontrol.

ViewUserControl(Of TModel) Represents the information that is required in order to builda strongly typed user control.

VirtualPathProviderViewEngine Represents an abstract base-class implementation of theIViewEngine interface.

WebFormView Represents the information that is needed to build a WebForms page in ASP.NET MVC.

WebFormViewEngine Represents a view engine that is used to render a WebForms page to the response.

WebViewPage Represents the properties and methods that are needed inorder to render a view that uses ASP.NET Razor syntax.

WebViewPage(Of TModel) Represents the properties and methods that are needed inorder to render a view that uses ASP.NET Razor syntax.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 154: ASP.Net

« Previous Next Chapter »

Interfaces

Interface Description

IActionFilter Defines the methods that are used in an action filter.

IActionInvoker Defines the contract for an action invoker, which is used to invoke anaction in response to an HTTP request.

IAuthorizationFilter Defines the methods that are required for an authorization filter.

IClientValidatable Provides a way for the ASP.NET MVC validation framework to discover atrun time whether a validator has support for client validation.

IController Defines the methods that are required for a controller.

IControllerActivator Provides fine-grained control over how controllers are instantiated usingdependency injection.

IControllerFactory Defines the methods that are required for a controller factory.

IDependencyResolver Defines the methods that simplify service location and dependencyresolution.

IExceptionFilter Defines the methods that are required for an exception filter.

IFilterProvider Provides an interface for finding filters.

IMetadataAware Provides an interface for exposing attributes to theAssociatedMetadataProvider class.

IModelBinder Defines the methods that are required for a model binder.

IModelBinderProvider Defines methods that enable dynamic implementations of model bindingfor classes that implement the IModelBinder interface.

IMvcFilter Defines members that specify the order of filters and whether multiplefilters are allowed.

IResultFilter Defines the methods that are required for a result filter.

IRouteWithArea Associates a route with an area in an ASP.NET MVC application.

ITempDataProvider Defines the contract for temporary-data providers that store data that isviewed on the next request.

IUnvalidatedValueProvider Represents an IValueProvider interface that can skip request validation.

IValueProvider Defines the methods that are required for a value provider in ASP.NETMVC.

IView Defines the methods that are required for a view.

IViewDataContainer Defines the methods that are required for a view data dictionary.

IViewEngine Defines the methods that are required for a view engine.

IViewLocationCache Defines the methods that are required in order to cache view locations inmemory.

IViewPageActivator Provides fine-grained control

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 155: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Demo

This is a Web Forms DemonstrationWeb Forms is one of the 3 programming models for creating ASP.NET web sites and web applications.

The other two programming models are Web Pages and MVC (Model, View, Controller).

This demonstration will teach you ASP.NET Web Forms by building a web site:

Create a web siteAdd files and foldersAdd a consistent lookAdd navigationAdd a database

Like to Read a Tutorial First?Many developers like to start learning a new technology by looking at a demonstration, but if you want to read the Web Forms tutorial first, go to theASP.NET Web Forms Tutorial.

Visual Web Developer (VWD)Visual Web Developer is a free development tool, tailor made for Web Forms (and MVC).

Visual Web Developer contains:

A web server markup language (Razor using VB or C#)A web server (IIS Express)A database server (SQL Server Compact)ASP.NET web controls and web componentsA full web development framework (ASP.NET)

You should install Visual Web Developer, to get the full benefits from this demo.

If you want to install Visual Web Developer, click on this picture:

After you have installed Visual Web Developer the first time, it pays to run the installation one more time, to install fixes and service packs.Just click on the link once more.

This Demonstration will Create a Web SiteIn this demo, we will use Visual Web Developer to develop a web site application.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 156: ASP.Net

« Previous Next Chapter »

Visual Web Developer supports two different development types:

Web ProjectsWeb Sites

Web Projects (We Will Not Do)Web Projects is the preferred development type for large projects, and for developers working in teams.

Web Projects are managed by a project file that keeps track of the content of a web site.

Web SitesA Web Site is simply a folder with files and subfolders. (There are no project files to keep track of the web project).

In this demo we will use Web Sites (not Web Projects).

If you are new to ASP.NET, a Web Site is easier to work with, and easier to copy, move, and share.

Create a Web SiteYou create a new Web Site in VWD by choosing "New Web Site..." from the main menu.

In the "New Web Site" dialog box, chose the Visual Basic (or Visual C#) template called "ASP.NET Empty Web Site":

Name the Web Site DemoWF and set the disk (File System) location to something like c:\w3schools_demo\DemoWF before clicking OK.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 157: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Demo

Learn ASP.NET Web Forms by building a web site from scratch.

Part I: Creating standard folders and a consistent style.

What We Will DoIn this chapter we will:

Create a new empty web siteCreate the necessary foldersCreate a standard style sheet for the siteCreate a standard layout for the siteCreate a home page for the site

1. Start With an Empty Web SiteIf you have followed this tutorial, you have already created a web site called DemoWF.

If not, you can create an empty web site with Visual Web Developer:

Start Visual Web DeveloperClick on "New Web Site..."Choose "Visual Basic (or Visual C#)Select the template "ASP.NET Empty Web Site"Set the file location to something like c:\w3schools_demo\DemoWF

2. Create FoldersIn the folder named "DemoWF" (your website), create 5 folders:

Account - for storing login and membership filesApp_Data - for storing databases and data filesImages - for storing imagesScripts - for storing browser scriptsStyles - for storing css styles

To create a new folder, right-click the root folder and select "New Folder..."

3. Create a Style SheetIn the "Styles" folder, create a new style sheet (CSS file) named "Site.css".

Put the following code inside the CSS file:

Site.css

body{font: "Trebuchet MS", Verdana, sans-serif;background-color: #5c87b2;color: #696969;}h1{color: #ffffff;}h2{border-bottom: 3px solid #cc9900;font: Georgia, serif;color: #996600;}#main{padding: 20px;background-color: #ffffff;border-radius: 0px 4px 4px 4px;

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 158: ASP.Net

}

The CSS file above defines the styles to be used used for

The HTML heading element <h1>The HTML body element <body>The HTML element with id="main"

4. Create a Master PageIn the root folder (DemoDW), create a master file named "Site.master".

To create a master file, right-click the root folder and select "Add New Item...". Then select "Master Page Visual Basic".

Put the following code inside the master page:

Site.master

<%@ Master Language="VB" %>

<!DOCTYPE html>

<html>

<head id="head" runat="server"><title></title><link href="Styles/Site.css" rel="stylesheet" type="text/css" /></head>

<body><form id="form1" runat="server"><h1>Demonstrating Web Forms</h1><div id="main"><asp:ContentPlaceHolder ID="MainContent" runat="server"/><p>&copy; <%=DateTime.Now.Year%> W3Schools. All rights reserved.</p></div></form></body></html>

The master page defines the standard layout of your web pages. It has a link to your style sheet file (Styles/Site.css), and a place holder for page content(asp:ContentPlaceHolder).

5. Create a Home PageIn your empty "DemoWF" folder, create a new Web Form, named "Default.aspx".

If you created a file with this name earlier, you can edit the existing file, or create a new file with a new name (like Default2.aspx).

To create a Web Form, right-click the root folder and select "Add New Item...". Then select "Web Form Visual Basic".

Put the following code inside the Web Form page:

Default.aspx

<%@ Page Title="Welcome" Language="VB" MasterPageFile="Site.master" %>

<asp:Content ID="Content" ContentPlaceHolderID="MainContent" Runat="Server">

<h2>Web Forms Main Ingredients</h2><p>A Home Page (Default.aspx)</p><p>A Layout File (Site.master)</p><p>A Style Sheet (Site.css)</p>

</asp:Content>

Run example »

The file starts with a reference to the master file. Inside an <asp:Content> element it contains normal HTML markup.

CongratulationsYou have created your first (ASP.NET Web Forms) web site, with a main page (the Default page), a common template for all your pages (the Master page),and a common style sheet (the CSS file).

In the next chapters of this tutorial, we will add navigation to the web site. Then we will add a database, and finally we will add login and security.

Web Forms File TypesBelow is a list of ASP.NET Web Forms most common file types.

Extention Description

.htm / .html HTML PagesWeb pages to be viewed directly by the browser

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 159: ASP.Net

« Previous Next Chapter »

.css Style SheetsDefines styles and formatting for the web site

.js JavaScriptsContains JavaScripts to be executed in the browser

.aspx Web FormsThe core of ASP.NET. Web pages with ASP.NET code.

.ascx Web User ControlsContains code fragments to be used by multiple pages

.asax Global ClassGlobal code (like startup code)

.asmx Web ServiceContains callable web services

.cs Class FilesContains code in C#

.vb Class FilesContains code in Vb (Visual Badsic)

.config Web ConfigurationContains configuration information for the web site

.master Master PagesDefine the global structure (look) of the web site

.sitemap XML Sitemap

.xml Data stored in XML format

.sdf SQL Server Compact Databases

.mdf SQL Server Expess (Accsess) Databases

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 160: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Adding a Menu

Learn ASP.NET Web Forms by building a web site from scratch.

Part II: Adding Navigation.

What We Will DoIn this chapter we will:

Add an about pageAdd a navigation menu

Add an About PageIn the "DemoWF" folder, create a new Web Form named "About.aspx".

Put the following code inside the file:

About.aspx

<%@ Page Title="About" Language="VB" MasterPageFile="Site.master" %>

<asp:Content ID="Content" ContentPlaceHolderID="MainContent" runat="Server">

<h2>About Us</h2> <p>Lorem Ipsum Porem Lorem Ipsum Porem</p>

</asp:Content>

The about file above contains a heading and a paragraph. Please feel free to edit the content.

Add a Navigation MenuIn the master file named "Site.master" and, edit the content.

Put the following code inside the master file:

Site.master

<%@ Master Language="VB" %><!DOCTYPE html>

<head id="head" runat="server"><title></title><link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /></head>

<body><form id="form1" runat="server"><ul id="menu"><li><a href="Default">Home</a></li> <li><a href="About">About</a></li> </ul>

<div id="main"><asp:ContentPlaceHolder ID="MainContent" runat="server"/><p>&copy; <%=DateTime.Now.year%> W3Schools. All rights reserved.</p></div></form></body></html>

The master file above, is a copy of the master file from the previous chapter, with an added unorderedlist (marked red).

Edit The Style SheetIn the Styles folder, edit your your style sheet (Site.css):

Put the following code inside the file:

Site.css

body{font: "Trebuchet MS", Verdana, sans-serif;background-color: #5c87b2;color: #696969;}h1{color: #ffffff;}

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 161: ASP.Net

« Previous Next Chapter »

h2{border-bottom: 3px solid #cc9900;font: Georgia, serif;color: #996600;}#main {padding: 20px;background-color: #ffffff;border-radius: 4px 4px 0 0;}

ul#menu{padding: 0px;position: relative;margin: 0;}

ul#menu li{display: inline;}

ul#menu li a {background-color: #e8eef4;padding: 10px 20px;text-decoration: none;line-height: 2.8em;color: #034af3;border-radius: 4px 4px 0 0;}

ul#menu li a:hover{background-color: #ffffff;}

The style sheet above, is a copy of the style sheet from the previous chapter, with added styles for anunordered list (marked red).

Edit the Home PageIn your "DemoWF" folder, edit the page (file) named "Default.aspx".

Put the following code inside the file:

Default.aspx

<%@ Page Title="Home" Language="VB" MasterPageFile="Site.master" %>

<asp:Content ID="Content" ContentPlaceHolderID="MainContent" Runat="Server">

<h1>Welcome</h1> <p>Lorem Ipsum Porem Lorem Ipsum Porem</p>

</asp:Content>

Run example »

Feel free to edit the content.

CongratulationsYou have added navigation to your website.

In the next chapter we will add a database.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 162: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Databases

Learn ASP.NET Web Forms by building a web site from scratch.

Part III: Adding a Database.

What We Will DoIn this chapter we will:

Create a databaseAdd data to the databaseCreate a page to list the database

Creating the DatabaseVisual Web Developer comes with a free SQL database called SQL Server Compact.

The database needed for this tutorial can be created with these simple steps:

Right-click the App_Data folder in the Solution Explorer windowSelect Add, New ItemSelect SQL Server Compact Local Database *Name the database Movies.sdf.Click the Add button

* If SQL Server Compact Local Database is not an option, you have not installed SQL Server Compacton your computer. Install it from this link: SQL Server Compact

Visual Web Developer automatically creates the database in the App_Data folder.

Note: In this tutorial it is expected that you have some knowledge about SQL databases. If you wantto study this topic first, please visit our SQL Tutorial.

Adding a Database TableDouble-clicking the Movies.sdf file in the App_Data folder will open a Database Explorer window.

To create a new table in the database, right-click the Tables folder, and select Create Table.

Create the following columns:

Column Type Allow Nulls

ID int (primary key) No

Title nvarchar(100) No

Director nvarchar(100) No

Date datetime No

Columns explained:

ID is an integer (whole number) used to identify each record in the table.

Title is a 100 character text column to store the name of the movie.

Director is a 100 character text column to store the director's name.

Date is a datetime column to store the release date of the movie.

After creating the columns described above, you must make the ID column the table's primary key(record identifier). To do this, click on the column name (ID) and select Primary Key. Also, in theColumn Properties window, set the Identity property to True:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 163: ASP.Net

When you have finished creating the table columns, save the table and name it Movies.

Adding Database RecordsYou can use Visual Web Developer to add some test records to the movie database.

Double-click the Movies.sdf file in the App_Data folder.

Right-click the Movie table in the Database Explorer window and select Show Table Data.

Add some records:

ID Title Director Date

1 Psycho Alfred Hitchcock 01.01.1960

2 La Dolce Vita Federico Fellini 01.01.1960

Note: The ID column is updated automatically. You should not edit it.

Adding Products PageIn the "DemoWF" folder, create a new Web Form named "Movies.aspx".

Put the following code inside the file:

Movies.aspx

<%@ Page Title="" Language="VB" MasterPageFile="Site.master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server"><h2>Products</h2>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="Movies">

<Columns><asp:BoundField DataField="ID" HeaderText="ID" /><asp:BoundField DataField="Title" HeaderText="Title" /><asp:BoundField DataField="Director" HeaderText="Director" /><asp:BoundField DataField="Date" HeaderText="Date" /></Columns>

</asp:GridView>

<asp:SqlDataSource ID="Movies" runat="server" ConnectionString="Data Source=|DataDirectory|\Movies.sdf"ProviderName="System.Data.SqlServerCe.4.0" SelectCommand="SELECT [ID], [Title], [Director], [Date] FROM [Movies]"></asp:SqlDataSource>

</asp:Content>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 164: ASP.Net

« Previous Next Chapter »

Edit the Master PageIn the Master Page (Site.master), locate the navigation menu.

Then add a new line to the menu:

Part of Site.master

<ul id="menu"><li><a href="Default.aspx">Home</a></li> <li><a href="Movies.aspx">Movies</a></li><li><a href="About.aspx">About</a></li> </ul>

CongratulationsYou have added a database to your web project.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 165: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - Tutorial

ASP.NET is a development framework for building web pages andweb sites with HTML, CSS, JavaScript and server scripting.

ASP.NET supports three different development models:Web Pages, MVC (Model View Controller), and Web Forms.

THIS TUTORIAL COVERS WEB FORMS

Web Pages MVC Web Forms

ASP.NET Framework

What is Web Forms?Web Forms is one of the 3 programming models for creating ASP.NET web sites and web applications.

The other two programming models are Web Pages and MVC (Model, View, Controller).

Web Forms is the oldest ASP.NET programming model, with event driven web pages written as a combination of HTML, server controls, and server code.

Web Forms are compiled and executed on the server, which generates the HTML that displays the web pages.

Web Forms comes with hundreds of different web controls and web components to build user-driven web sites with data access.

Where to Start?Many developers like to start learning a new technology by looking at working examples.

If you want to take a look at a working Web Forms examples, follow the ASP.NET Web Forms Demo.

Visual Web Developer (VWD)Visual Web Developer is a free development tool, tailor made for Web Forms (and MVC).

Visual Web Developer contains:

A web server markup language (Razor using VB or C#)A web server (IIS Express)A database server (SQL Server Compact)ASP.NET web controls and web componentsA full web development framework (ASP.NET)

You should install Visual Web Developer, to get the full benefits from this tutorial.

If you want to install VWD, go to the chapter ASP.NET Web Forms Demo.

ASP.NET ReferencesAt the end of this tutorial you will find a complete ASP.NET reference with objects, components, properties and methods.

ASP.NET Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 166: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - HTML Pages

A simple ASP.NET page looks just like an ordinary HTML page.

Hello W3SchoolsTo start learning ASP.NET, we will construct a very simple HTML page that will display "Hello W3Schools" in an Internet browser like this:

Hello W3Schools!

Hello W3Schools in HTMLThis code displays the example as an HTML page:

<html><body bgcolor="yellow"><center><h2>Hello W3Schools!</h2></center></body></html>

If you want to try it yourself, save the code in a file called "firstpage.htm", and create a link to the file like this: firstpage.htm

Hello W3Schools in ASP.NETThe simplest way to convert an HTML page into an ASP.NET page is to copy the HTML file to a new file with an .aspx extension.

This code displays our example as an ASP.NET page:

<html><body bgcolor="yellow"><center><h2>Hello W3Schools!</h2></center></body></html>

If you want to try it yourself, save the code in a file called "firstpage.aspx", and create a link to the file like this: firstpage.aspx

How Does it Work?Fundamentally an ASP.NET page is just the same as an HTML page.

An HTML page has the extension .htm. If a browser requests an HTML page from the server, the server sends the page to the browser without anymodifications.

An ASP.NET page has the extension .aspx. If a browser requests an ASP.NET page, the server processes any executable code in the page, before the resultis sent back to the browser.

The ASP.NET page above does not contain any executable code, so nothing is executed. In the next examples we will add some executable code to the pageto demonstrate the difference between static HTML pages and dynamic ASP pages.

Classic ASPActive Server Pages (ASP) has been around for several years. With ASP, executable code can be placed inside HTML pages.

Previous versions of ASP (before ASP .NET) are often called Classic ASP.

ASP.NET is not fully compatible with Classic ASP, but most Classic ASP pages will work fine as ASP.NET pages, with only minor changes.

If you want to learn more about Classic ASP, please visit our ASP Tutorial.

Dynamic Page in Classic ASPTo demonstrate how ASP can display pages with dynamic content, we have added some executable code (in red) to the previous example:

<html><body bgcolor="yellow"><center><h2>Hello W3Schools!</h2><p><%Response.Write(now())%></p></center></body></html>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 167: ASP.Net

« Previous Next Chapter »

The code inside the <% --%> tags is executed on the server.

Response.Write is ASP code for writing something to the HTML output stream.

Now() is a function returning the servers current date and time.

If you want to try it yourself, save the code in a file called "dynpage.asp", and create a link to the file like this: dynpage.asp

Dynamic Page in ASP .NETThis following code displays our example as an ASP.NET page:

<html><body bgcolor="yellow"><center><h2>Hello W3Schools!</h2><p><%Response.Write(now())%></p></center></body></html>

If you want to try it yourself, save the code in a file called "dynpage.aspx", and create a link to the file like this: dynpage.aspx

ASP.NET vs Classic ASPThe previous examples didn't demonstrate any differences between ASP.NET and Classic ASP.

As you can see from the two latest examples there are no differences between the two ASP and ASP.NET pages.

In the next chapters you will see how server controls make ASP.NET more powerful than Classic ASP.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 168: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Server Controls

Server controls are tags that are understood by the server.

Limitations in Classic ASPThe listing below was copied from the previous chapter:

<html><body bgcolor="yellow"><center><h2>Hello W3Schools!</h2><p><%Response.Write(now())%></p></center></body></html>

The code above illustrates a limitation in Classic ASP: The code block has to be placed where you want the output to appear.

With Classic ASP it is impossible to separate executable code from the HTML itself. This makes the page difficult to read, and difficult to maintain.

ASP.NET - Server ControlsASP.NET has solved the "spaghetti-code" problem described above with server controls.

Server controls are tags that are understood by the server.

There are three kinds of server controls:

HTML Server Controls - Traditional HTML tagsWeb Server Controls - New ASP.NET tagsValidation Server Controls - For input validation

ASP.NET - HTML Server ControlsHTML server controls are HTML tags understood by the server.

HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTMLelement. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The idreference can be used to manipulate the server control at run time.

Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The runat="server" attribute indicates that the form shouldbe processed on the server. It also indicates that the enclosed controls can be accessed by server scripts.

In the following example we declare an HtmlAnchor server control in an .aspx file. Then we manipulate the HRef attribute of the HtmlAnchor control in anevent handler (an event handler is a subroutine that executes code for a given event). The Page_Load event is one of many events that ASP.NETunderstands:

<script runat="server">Sub Page_Loadlink1.HRef="http://www.w3schools.com"End Sub</script>

<html><body>

<form runat="server"><a id="link1" runat="server">Visit W3Schools!</a></form>

</body></html>

The executable code itself has been moved outside the HTML.

ASP.NET - Web Server ControlsWeb server controls are special ASP.NET tags understood by the server.

Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to work. However, Web servercontrols do not necessarily map to any existing HTML elements and they may represent more complex elements.

The syntax for creating a Web server control is:

<asp:control_name id="some_id" runat="server" />

In the following example we declare a Button server control in an .aspx file. Then we create an event handler for the Click event which changes the text onthe button:

<script runat="server">Sub submit(Source As Object, e As EventArgs)button1.Text="You clicked me!"End Sub

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 169: ASP.Net

« Previous Next Chapter »

</script>

<html><body>

<form runat="server"><asp:Button id="button1" Text="Click me!"runat="server" OnClick="submit"/></form>

</body></html>

ASP.NET - Validation Server ControlsValidation server controls are used to validate user-input. If the user-input does not pass validation, it will display an error message to the user.

Each validation control performs a specific type of validation (like validating against a specific value or a range of values).

By default, page validation is performed when a Button, ImageButton, or LinkButton control is clicked. You can prevent validation when a button control isclicked by setting the CausesValidation property to false.

The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

In the following example we declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If validation fails, the text "Thevalue must be from 1 to 100!" will be displayed in the RangeValidator control:

Example

<html><body>

<form runat="server"><p>Enter a number from 1 to 100:<asp:TextBox id="tbox1" runat="server" /><br /><br /><asp:Button Text="Submit" runat="server" /></p>

<p><asp:RangeValidatorControlToValidate="tbox1"MinimumValue="1"MaximumValue="100"Type="Integer"Text="The value must be from 1 to 100!"runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 170: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - Events

An Event Handler is a subroutine that executes code for a given event.

ASP.NET - Event HandlersLook at the following code:

<%lbl1.Text="The date and time is " & now()%>

<html><body><form runat="server"><h3><asp:label id="lbl1" runat="server" /></h3></form></body></html>

When will the code above be executed? The answer is: "You don't know..."

The Page_Load EventThe Page_Load event is one of many events that ASP.NET understands. The Page_Load event is triggered when a page loads, and ASP.NET willautomatically call the subroutine Page_Load, and execute the code inside it:

Example

<script runat="server">Sub Page_Loadlbl1.Text="The date and time is " & now()End Sub</script>

<html><body><form runat="server"><h3><asp:label id="lbl1" runat="server" /></h3></form></body></html>

Show example »

Note: The Page_Load event contains no object references or event arguments!

The Page.IsPostBack PropertyThe Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code in the Page_Load subroutine only the FIRST time the pageis loaded, you can use the Page.IsPostBack property. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true, the page isposted back to the server (i.e. from a button click on a form):

Example

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then lbl1.Text="The date and time is " & now()end ifEnd Sub

Sub submit(s As Object, e As EventArgs)lbl2.Text="Hello World!"End Sub</script>

<html><body><form runat="server"><h3><asp:label id="lbl1" runat="server" /></h3><h3><asp:label id="lbl2" runat="server" /></h3><asp:button text="Submit" onclick="submit" runat="server" /></form></body></html>

Show example »

The example above will write the "The date and time is...." message only the first time the page is loaded. When a user clicks on the Submit button, thesubmit subroutine will write "Hello World!" to the second label, but the date and time in the first label will not change.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 171: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - HTML Forms

All server controls must appear within a <form> tag, and the <form> tag must containthe runat="server" attribute.

ASP.NET Web FormsAll server controls must appear within a <form> tag, and the <form> tag must contain therunat="server" attribute. The runat="server" attribute indicates that the form should be processed onthe server. It also indicates that the enclosed controls can be accessed by server scripts:

<form runat="server">

...HTML + server controls

</form>

Note: The form is always submitted to the page itself. If you specify an action attribute, it is ignored.If you omit the method attribute, it will be set to method="post" by default. Also, if you do not specifythe name and id attributes, they are automatically assigned by ASP.NET.

Note: An .aspx page can only contain ONE <form runat="server"> control!

If you select view source in an .aspx page containing a form with no name, method, action, or idattribute specified, you will see that ASP.NET has added these attributes to the form. It lookssomething like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">

...some code

</form>

Submitting a FormA form is most often submitted by clicking on a button. The Button server control in ASP.NET has thefollowing format:

<asp:Button id="id" text="label" OnClick="sub" runat="server" />

The id attribute defines a unique name for the button and the text attribute assigns a label to thebutton. The onClick event handler specifies a named subroutine to execute.

In the following example we declare a Button control in an .aspx file. A button click runs a subroutinewhich changes the text on the button:

Example

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 172: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - Maintaining the ViewState

You may save a lot of coding by maintaining the ViewState of the objects in your WebForm.

Maintaining the ViewStateWhen a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted aform with a lot of information and the server comes back with an error. You will have to go back to theform and correct the information. You click the back button, and what happens.......ALL form valuesare CLEARED, and you will have to start all over again! The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together with allform values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicatesthe status of the page when submitted to the server. The status is defined through a hidden fieldplaced on each page with a <form runat="server"> control. The source could look something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0"><input type="hidden" name="__VIEWSTATE"value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

</form>

Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintainthe ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspxpage or add the attribute EnableViewState="false" to any control.

Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submitbutton, the form value will disappear:

Example

<html><body>

<form action="demo_classicasp.aspx" method="post">Your name: <input type="text" name="fname" size="20"><input type="submit" value="Submit"></form><%dim fnamefname=Request.Form("fname")If fname<>"" ThenResponse.Write("Hello " & fname & "!")End If%>

</body></html>

Show example »

Here is the new ASP .NET way. When you click on the submit button, the form value will NOTdisappear:

Example

Click view source in the right frame of the example to see that ASP .NET has added a hidden field inthe form to maintain the ViewState

<script runat="server">Sub submit(sender As Object, e As EventArgs)lbl1.Text="Hello " & txt1.Text & "!"End Sub</script>

<html><body>

<form runat="server">Your name: <asp:TextBox id="txt1" runat="server" /><asp:Button OnClick="submit" Text="Submit" runat="server" /><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 173: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The TextBox Control

The TextBox control is used to create a text box where the user can input text.

The TextBox ControlThe TextBox control is used to create a text box where the user can input text.

The TextBox control's attributes and properties are listed in our web controls reference page.

The example below demonstrates some of the attributes you may use with the TextBox control:

Example

<html><body>

<form runat="server">

A basic TextBox:<asp:TextBox id="tb1" runat="server" /><br /><br />

A password TextBox:<asp:TextBox id="tb2" TextMode="password" runat="server" /><br /><br />

A TextBox with text:<asp:TextBox id="tb4" Text="Hello World!" runat="server" /><br /><br />

A multiline TextBox:<asp:TextBox id="tb3" TextMode="multiline" runat="server" /><br /><br />

A TextBox with height:<asp:TextBox id="tb6" rows="5" TextMode="multiline"runat="server" /><br /><br />

A TextBox with width:<asp:TextBox id="tb5" columns="30" runat="server" />

</form>

</body></html>

Show example »

Add a ScriptThe contents and settings of a TextBox control may be changed by server scripts when a form is submitted. A form can be submitted by clicking on a buttonor when a user changes the value in the TextBox control.

In the following example we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered,the submit subroutine is executed. The submit subroutine writes a text to the Label control:

Example

<script runat="server">Sub submit(sender As Object, e As EventArgs)lbl1.Text="Your name is " & txt1.TextEnd Sub</script>

<html><body>

<form runat="server">Enter your name:<asp:TextBox id="txt1" runat="server" /><asp:Button OnClick="submit" Text="Submit" runat="server" /><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

In the following example we declare one TextBox control and one Label control in an .aspx file. When you change the value in the TextBox and either clickoutside the TextBox or press the Tab key, the change subroutine is executed. The submit subroutine writes a text to the Label control:

Example

<script runat="server">Sub change(sender As Object, e As EventArgs)lbl1.Text="You changed text to " & txt1.Text

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 174: ASP.Net

« Previous Next Chapter »

End Sub</script>

<html><body>

<form runat="server">Enter your name:<asp:TextBox id="txt1" runat="server"text="Hello World!"ontextchanged="change" autopostback="true"/><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 175: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - The Button Control

The Button control is used to display a push button.

The Button ControlThe Button control is used to display a push button. The push button may be a submit button or a command button. By default, this control is a submitbutton.

A submit button does not have a command name and it posts the page back to the server when it is clicked. It is possible to write an event handler tocontrol the actions performed when the submit button is clicked.

A command button has a command name and allows you to create multiple Button controls on a page. It is possible to write an event handler to control theactions performed when the command button is clicked.

The Button control's attributes and properties are listed in our web controls reference page.

The example below demonstrates a simple Button control:

<html><body>

<form runat="server"><asp:Button id="b1" Text="Submit" runat="server" /></form>

</body></html>

Add a ScriptA form is most often submitted by clicking on a button.

In the following example we declare one TextBox control, one Button control, and one Label control in an .aspx file. When the submit button is triggered,the submit subroutine is executed. The submit subroutine writes a text to the Label control:

Example

<script runat="server">Sub submit(sender As Object, e As EventArgs)lbl1.Text="Your name is " & txt1.TextEnd Sub</script>

<html><body>

<form runat="server">Enter your name:<asp:TextBox id="txt1" runat="server" /><asp:Button OnClick="submit" Text="Submit" runat="server" /><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 176: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - Data Binding

We may use data binding to fill lists with selectable items from an imported data source, like a database, an XML file, or a script.

Data BindingThe following controls are list controls which support data binding:

asp:RadioButtonListasp:CheckBoxListasp:DropDownListasp:Listbox

The selectable items in each of the above controls are usually defined by one or more asp:ListItem controls, like this:

<html><body>

<form runat="server"><asp:RadioButtonList id="countrylist" runat="server"><asp:ListItem value="N" text="Norway" /><asp:ListItem value="S" text="Sweden" /><asp:ListItem value="F" text="France" /><asp:ListItem value="I" text="Italy" /></asp:RadioButtonList></form>

</body></html>

However, with data binding we may use a separate source, like a database, an XML file, or a script to fill the list with selectable items.

By using an imported source, the data is separated from the HTML, and any changes to the items are made in the separate data source.

In the next three chapters, we will describe how to bind data from a scripted data source.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 177: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The ArrayList Object

The ArrayList object is a collection of items containing a single data value.

Try it Yourself - Examples

ArrayList DropDownList

ArrayList RadioButtonList

Create an ArrayListThe ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.

The following code creates a new ArrayList object named mycountries and four items are added:

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy")end ifend sub</script>

By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with theTrimToSize() method:

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize()end ifend sub</script>

An ArrayList can also be sorted alphabetically or numerically with the Sort() method:

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort()end ifend sub</script>

To sort in reverse order, apply the Reverse() method after the Sort() method:

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() mycountries.Reverse()end ifend sub</script>

Data Binding to an ArrayListAn ArrayList object may automatically generate the text and values to the following controls:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 178: ASP.Net

« Previous Next Chapter »

asp:RadioButtonListasp:CheckBoxListasp:DropDownListasp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without anyasp:ListItem elements) in an .aspx page:

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" /></form>

</body></html>

Then add the script that builds the list and binds the values in the list to the RadioButtonList control:

Example

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() rb.DataSource=mycountries rb.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" /></form>

</body></html>

Show example »

The DataSource property of the RadioButtonList control is set to the ArrayList and it defines the datasource of the RadioButtonList control. The DataBind() method of the RadioButtonList control binds thedata source with the RadioButtonList control.

Note: The data values are used as both the Text and Value properties for the control. To add Valuesthat are different from the Text, use either the Hashtable object or the SortedList object.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 179: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The Hashtable Object

The Hashtable object contains items in key/value pairs.

Try it Yourself - Examples

Hashtable RadiobuttonList 1

Hashtable RadiobuttonList 2

Hashtable DropDownList

Create a HashtableThe Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching throughtheir keys.

Items are added to the Hashtable with the Add() method.

The following code creates a Hashtable named mycountries and four elements are added:

<script runat="server">Sub Page_Loadif Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy")end ifend sub</script>

Data BindingA Hashtable object may automatically generate the text and values to the following controls:

asp:RadioButtonListasp:CheckBoxListasp:DropDownListasp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form>

</body></html>

Then add the script that builds the list:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form>

</body></html>

Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appearin a label:

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 180: ASP.Net

« Previous Next Chapter »

Example

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Note: You cannot choose the sort order of the items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 181: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim navigate=New Hashtable navigate.Add("RadioButtonList","control_radiobuttonlist.asp") navigate.Add("CheckBoxList","control_checkboxlist.asp") navigate.Add("DropDownList","control_dropdownlist.asp") navigate.Add("ListBox","control_listbox.asp") rb.DataSource=navigate rb.DataValueField="Value" rb.DataTextField="Key" rb.DataBind()end ifend sub

sub navigate(s as Object, e As EventArgs)response.redirect(rb.SelectedItem.Value)end sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="navigate" /></form>

</body></html>

CheckBoxListDropDownListRadioButtonListListBox

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 182: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") dd.DataSource=mycountries dd.DataValueField="Key" dd.DataTextField="Value" dd.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & dd.SelectedItem.Textend sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:DropDownList id="dd" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage"/><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

Norway

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 183: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage"/><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

NorwayFranceItalySweden

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 184: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The SortedList Object

The SortedList object combines the features of both the ArrayList object and the Hashtable object.

Try it Yourself - Examples

SortedList RadiobuttonList 1

SortedList RadiobuttonList 2

SortedList DropDownList

The SortedList ObjectThe SortedList object contains items in key/value pairs. A SortedList object automatically sort the items in alphabetic or numeric order.

Items are added to the SortedList with the Add() method. A SortedList can be sized to its final size with the TrimToSize() method.

The following code creates a SortedList named mycountries and four elements are added:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy")end ifend sub</script>

Data BindingA SortedList object may automatically generate the text and values to the following controls:

asp:RadioButtonListasp:CheckBoxListasp:DropDownListasp:Listbox

To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form>

</body></html>

Then add the script that builds the list:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form>

</body></html>

Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appearin a label:

Example

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 185: ASP.Net

« Previous Next Chapter »

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 186: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage"/><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

FranceItalyNorwaySweden

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 187: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim navigate=New SortedList navigate.Add("RadioButtonList","control_radiobuttonlist.asp") navigate.Add("CheckBoxList","control_checkboxlist.asp") navigate.Add("DropDownList","control_dropdownlist.asp") navigate.Add("ListBox","control_listbox.asp") rb.DataSource=navigate rb.DataValueField="Value" rb.DataTextField="Key" rb.DataBind()end ifend sub

sub navigate(s as Object, e As EventArgs)response.redirect(rb.SelectedItem.Value)end sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="navigate" /></form>

</body></html>

CheckBoxListDropDownListListBoxRadioButtonList

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 188: ASP.Net

ASP Source: Output Result:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") dd.DataSource=mycountries dd.DataValueField="Key" dd.DataTextField="Value" dd.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & dd.SelectedItem.Textend sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:DropDownList id="dd" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage"/><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

France

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 189: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - XML Files

We can bind an XML file to a list control.

An XML FileHere is an XML file named "countries.xml":

<?xml version="1.0" encoding="ISO-8859-1"?>

<countries>

<country> <text>Norway</text> <value>N</value></country>

<country> <text>Sweden</text> <value>S</value></country>

<country> <text>France</text> <value>F</value></country>

<country> <text>Italy</text> <value>I</value></country>

</countries>

Take a look at the XML file: countries.xml

Bind a DataSet to a List ControlFirst, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspxpage:

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml"))end ifend sub

To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" /></form>

</body></html>

Then add the script that builds the XML DataSet:

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /></form>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 190: ASP.Net

« Previous Next Chapter »

</body></html>

Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appearin a label:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind()end ifend sub

sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub</script>

<html><body>

<form runat="server"><asp:RadioButtonList id="rb" runat="server"AutoPostBack="True" onSelectedIndexChanged="displayMessage" /><p><asp:label id="lbl1" runat="server" /></p></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 191: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The Repeater Control

The Repeater control is used to display a repeated list of items that are bound to thecontrol.

Bind a DataSet to a Repeater ControlThe Repeater control is used to display a repeated list of items that are bound to the control. TheRepeater control may be bound to a database table, an XML file, or another list of items. Here we willshow how to bind an XML file to a Repeater control.

We will use the following XML file in our examples ("cdcatalog.xml"):

<?xml version="1.0" encoding="ISO-8859-1"?>

<catalog><cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year></cd><cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year></cd><cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year></cd><cd> <title>Still got the blues</title> <artist>Gary Moore</artist> <country>UK</country> <company>Virgin records</company> <price>10.20</price> <year>1990</year></cd><cd> <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year></cd></catalog>

Take a look at the XML file: cdcatalog.xml

First, import the "System.Data" namespace. We need this namespace to work with DataSet objects.Include the following directive at the top of an .aspx page:

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is firstloaded:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))end ifend sub

Then we create a Repeater control in an .aspx page. The contents of the <HeaderTemplate> elementare rendered first and only once within the output, then the contents of the <ItemTemplate> elementare repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> elementare rendered once within the output:

<html><body>

<form runat="server"><asp:Repeater id="cdcatalog" runat="server">

<HeaderTemplate>...</HeaderTemplate>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 192: ASP.Net

<ItemTemplate>...</ItemTemplate>

<FooterTemplate>...</FooterTemplate>

</asp:Repeater></form>

</body></html>

Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the Repeatercontrol. We also fill the Repeater control with HTML tags and bind the data items to the cells inthe<ItemTemplate> section with the <%#Container.DataItem("fieldname")%> method:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:Repeater id="cdcatalog" runat="server">

<HeaderTemplate><table border="1" width="100%"><tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr></HeaderTemplate>

<ItemTemplate><tr><td><%#Container.DataItem("title")%></td><td><%#Container.DataItem("artist")%></td><td><%#Container.DataItem("country")%></td><td><%#Container.DataItem("company")%></td><td><%#Container.DataItem("price")%></td><td><%#Container.DataItem("year")%></td></tr></ItemTemplate>

<FooterTemplate></table></FooterTemplate>

</asp:Repeater></form>

</body></html>

Show example »

Using the <AlternatingItemTemplate>You can add an <AlternatingItemTemplate> element after the <ItemTemplate> element to describethe appearance of alternating rows of output. In the following example each other row in the table willbe displayed in a light grey color:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server">

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 193: ASP.Net

<asp:Repeater id="cdcatalog" runat="server">

<HeaderTemplate><table border="1" width="100%"><tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr></HeaderTemplate>

<ItemTemplate><tr><td><%#Container.DataItem("title")%></td><td><%#Container.DataItem("artist")%></td><td><%#Container.DataItem("country")%></td><td><%#Container.DataItem("company")%></td><td><%#Container.DataItem("price")%></td><td><%#Container.DataItem("year")%></td></tr></ItemTemplate>

<AlternatingItemTemplate><tr bgcolor="#e8e8e8"><td><%#Container.DataItem("title")%></td><td><%#Container.DataItem("artist")%></td><td><%#Container.DataItem("country")%></td><td><%#Container.DataItem("company")%></td><td><%#Container.DataItem("price")%></td><td><%#Container.DataItem("year")%></td></tr></AlternatingItemTemplate>

<FooterTemplate></table></FooterTemplate>

</asp:Repeater></form>

</body></html>

Show example »

Using the <SeparatorTemplate>The <SeparatorTemplate> element can be used to describe a separator between each record. Thefollowing example inserts a horizontal line between each table row:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:Repeater id="cdcatalog" runat="server">

<HeaderTemplate><table border="0" width="100%"><tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr></HeaderTemplate>

<ItemTemplate><tr><td><%#Container.DataItem("title")%></td><td><%#Container.DataItem("artist")%></td><td><%#Container.DataItem("country")%></td><td><%#Container.DataItem("company")%></td><td><%#Container.DataItem("price")%></td><td><%#Container.DataItem("year")%></td></tr></ItemTemplate>

<SeparatorTemplate><tr><td colspan="6"><hr /></td></tr></SeparatorTemplate>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 194: ASP.Net

« Previous Next Chapter »

<FooterTemplate></table></FooterTemplate>

</asp:Repeater></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 195: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - The DataList Control

The DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, theDataList control adds a table around the data items by default.

Bind a DataSet to a DataList ControlThe DataList control is, like the Repeater control, used to display a repeated list of items that are bound to the control. However, the DataList control adds atable around the data items by default. The DataList control may be bound to a database table, an XML file, or another list of items. Here we will show howto bind an XML file to a DataList control.

We will use the following XML file in our examples ("cdcatalog.xml"):

<?xml version="1.0" encoding="ISO-8859-1"?>

<catalog><cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year></cd><cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year></cd><cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year></cd><cd> <title>Still got the blues</title> <artist>Gary Moore</artist> <country>UK</country> <company>Virgin records</company> <price>10.20</price> <year>1990</year></cd><cd> <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year></cd></catalog>

Take a look at the XML file: cdcatalog.xml

First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspxpage:

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))end ifend sub

Then we create a DataList in an .aspx page. The contents of the <HeaderTemplate> element are rendered first and only once within the output, then thecontents of the <ItemTemplate> element are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element arerendered once within the output:

<html><body>

<form runat="server"><asp:DataList id="cdcatalog" runat="server">

<HeaderTemplate>...</HeaderTemplate>

<ItemTemplate>...</ItemTemplate>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 196: ASP.Net

<FooterTemplate>...</FooterTemplate>

</asp:DataList></form>

</body></html>

Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the DataList control. We also fill the DataList control with a<HeaderTemplate> that contains the header of the table, an <ItemTemplate> that contains the data items to display, and a <FooterTemplate> thatcontains a text. Note that the gridlines attribute of the DataList is set to "both" to display table borders:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:DataList id="cdcatalog"gridlines="both" runat="server">

<HeaderTemplate>My CD Catalog</HeaderTemplate>

<ItemTemplate>"<%#Container.DataItem("title")%>" of<%#Container.DataItem("artist")%> -$<%#Container.DataItem("price")%></ItemTemplate>

<FooterTemplate>Copyright Hege Refsnes</FooterTemplate>

</asp:DataList></form>

</body></html>

Show example »

Using StylesYou can also add styles to the DataList control to make the output more fancy:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack then dim mycdcatalog=New DataSet mycdcatalog.ReadXml(MapPath("cdcatalog.xml")) cdcatalog.DataSource=mycdcatalog cdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:DataList id="cdcatalog"runat="server"cellpadding="2"cellspacing="2"borderstyle="inset"backcolor="#e8e8e8"width="100%"headerstyle-font-name="Verdana"headerstyle-font-size="12pt"headerstyle-horizontalalign="center"headerstyle-font-bold="true"itemstyle-backcolor="#778899"itemstyle-forecolor="#ffffff"footerstyle-font-size="9pt"footerstyle-font-italic="true">

<HeaderTemplate>My CD Catalog

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 197: ASP.Net

« Previous Next Chapter »

</HeaderTemplate>

<ItemTemplate>"<%#Container.DataItem("title")%>" of<%#Container.DataItem("artist")%> -$<%#Container.DataItem("price")%></ItemTemplate>

<FooterTemplate>Copyright Hege Refsnes</FooterTemplate>

</asp:DataList></form>

</body></html>

Show example »

Using the <AlternatingItemTemplate>You can add an <AlternatingItemTemplate> element after the <ItemTemplate> element to describe the appearance of alternating rows of output. You maystyle the data in the <AlternatingItemTemplate> section within the DataList control:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()end ifend sub</script>

<html><body>

<form runat="server"><asp:DataList id="cdcatalog"runat="server"cellpadding="2"cellspacing="2"borderstyle="inset"backcolor="#e8e8e8"width="100%"headerstyle-font-name="Verdana"headerstyle-font-size="12pt"headerstyle-horizontalalign="center"headerstyle-font-bold="True"itemstyle-backcolor="#778899"itemstyle-forecolor="#ffffff"alternatingitemstyle-backcolor="#e8e8e8"alternatingitemstyle-forecolor="#000000"footerstyle-font-size="9pt"footerstyle-font-italic="True">

<HeaderTemplate>My CD Catalog</HeaderTemplate>

<ItemTemplate>"<%#Container.DataItem("title")%>" of<%#Container.DataItem("artist")%> -$<%#Container.DataItem("price")%></ItemTemplate>

<AlternatingItemTemplate>"<%#Container.DataItem("title")%>" of<%#Container.DataItem("artist")%> -$<%#Container.DataItem("price")%></AlternatingItemTemplate>

<FooterTemplate>&copy; Hege Refsnes</FooterTemplate>

</asp:DataList></form>

</body></html>

Show example »

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 198: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Database Connection

ADO.NET is also a part of the .NET Framework. ADO.NET is used to handle data access.With ADO.NET you can work with databases.

Try it Yourself - Examples

Database connection - Bind to a DataList control

Database connection - Bind to a Repeater control

What is ADO.NET?ADO.NET is a part of the .NET FrameworkADO.NET consists of a set of classes used to handle data accessADO.NET is entirely based on XMLADO.NET has, unlike ADO, no Recordset object

Create a Database ConnectionWe are going to use the Northwind database in our examples.

First, import the "System.Data.OleDb" namespace. We need this namespace to work with MicrosoftAccess and other OLE DB database providers. We will create the connection to the database in thePage_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connectionstring which identifies the OLE DB provider and the location of the database. Then we open thedatabase connection:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconndbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()end sub</script>

Note: The connection string must be a continuous string without a line break!

Create a Database CommandTo specify the records to retrieve from the database, we will create a dbcomm variable as a newOleDbCommand class. The OleDbCommand class is for issuing SQL queries against database tables:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconn,sql,dbcommdbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)end sub</script>

Create a DataReaderThe OleDbDataReader class is used to read a stream of records from a data source. A DataReader iscreated by calling the ExecuteReader method of the OleDbCommand object:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()end sub</script>

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 199: ASP.Net

« Previous Next Chapter »

Bind to a Repeater ControlThen we bind the DataReader to a Repeater control:

Example

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()customers.DataSource=dbreadcustomers.DataBind()dbread.Close()dbconn.Close()end sub</script>

<html><body>

<form runat="server"><asp:Repeater id="customers" runat="server">

<HeaderTemplate><table border="1" width="100%"><tr><th>Companyname</th><th>Contactname</th><th>Address</th><th>City</th></tr></HeaderTemplate>

<ItemTemplate><tr><td><%#Container.DataItem("companyname")%></td><td><%#Container.DataItem("contactname")%></td><td><%#Container.DataItem("address")%></td><td><%#Container.DataItem("city")%></td></tr></ItemTemplate>

<FooterTemplate></table></FooterTemplate>

</asp:Repeater></form>

</body></html>

Show example »

Close the Database ConnectionAlways close both the DataReader and database connection after access to the database is no longerrequired:

dbread.Close()dbconn.Close()

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 200: ASP.Net

ASP Source: Output Result:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=NewOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="& server.mappath("/db/northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()customers.DataSource=dbreadcustomers.DataBind()dbread.Close()dbconn.Close()end sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:Repeater id="customers" runat="server">

<HeaderTemplate><table border="1" width="100%"><tr bgcolor="#b0c4de"><th>Companyname</th><th>Contactname</th><th>Address</th><th>City</th></tr></HeaderTemplate>

<ItemTemplate>

Companyname Contactname Address CityAlfredsFutterkiste Maria Anders Obere Str. 57 Berlin

Berglundssnabbköp

ChristinaBerglund

Berguvsvägen8 Luleå

Centro comercialMoctezuma

FranciscoChang

Sierras deGranada 9993

MéxicoD.F.

Ernst Handel Roland Mendel Kirchgasse 6 Graz FISSA FabricaInter. SalchichasS.A.

Diego Roel C/ Moralzarzal,86 Madrid

GalerÃa delgastrónomo

EduardoSaavedra

Rambla deCataluña, 23 Barcelona

Island Trading Helen Bennett Garden HouseCrowther Way Cowes

Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg Laughing BacchusWine Cellars

YoshiTannamuri 1900 Oak St. Vancouver

MagazziniAlimentari Riuniti

GiovanniRovelli

Via Ludovico ilMoro 22 Bergamo

North/South SimonCrowther

South House300Queensbridge

London

Parisspécialités Marie Bertrand 265, boulevard

Charonne Paris

RattlesnakeCanyon Grocery Paula Wilson 2817 Milton

Dr. Albuquerque

Simons bistro Jytte Petersen Vinbæltet 34 København

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 201: ASP.Net

ASP Source: Output Result:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=NewOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="& server.mappath("/db/northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()customers.DataSource=dbreadcustomers.DataBind()dbread.Close()dbconn.Close()end sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:DataListid="customers"runat="server"cellpadding="2"cellspacing="2"borderstyle="inset"backcolor="#e8e8e8"width="100%"headerstyle-font-name="Verdana"headerstyle-font-size="12pt"headerstyle-horizontalalign="center"headerstyle-font-bold="True"itemstyle-backcolor="#778899"

Customers TableAlfreds Futterkiste in Obere Str. 57, BerlinBerglunds snabbköp in Berguvsvägen 8, LuleÃ¥Centro comercial Moctezuma in Sierras de Granada 9993,México D.F.Ernst Handel in Kirchgasse 6, GrazFISSA Fabrica Inter. Salchichas S.A. in C/ Moralzarzal, 86,MadridGalerÃa del gastrónomo in Rambla de Cataluña, 23, BarcelonaIsland Trading in Garden House Crowther Way, CowesKöniglich Essen in Maubelstr. 90, BrandenburgLaughing Bacchus Wine Cellars in 1900 Oak St., VancouverMagazzini Alimentari Riuniti in Via Ludovico il Moro 22,BergamoNorth/South in South House 300 Queensbridge, LondonParis spécialités in 265, boulevard Charonne, ParisRattlesnake Canyon Grocery in 2817 Milton Dr., AlbuquerqueSimons bistro in Vinbæltet 34, KøbenhavnThe Big Cheese in 89 Jefferson Way Suite 2, PortlandVaffeljernet in Smagsløget 45, Ã…rhusWolski Zajazd in ul. Filtrowa 68, WarszawaSource: Northwind Database

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 202: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - Master Pages

Master pages provide templates for other pages on your web site.

Master PagesMaster pages allow you to create a consistent look and behavior for all the pages (or group of pages) in your web application.

A master page provides a template for other pages, with shared layout and functionality. The master page defines placeholders for the content, which canbe overridden by content pages. The output result is a combination of the master page and the content page.

The content pages contains the content you want to display.

When users request the content page, ASP.NET merges the pages to produce output that combines the layout of the master page with the content of thecontent page.

Master Page Example

<%@ Master %>

<html><body><h1>Standard Header For All Pages</h1><asp:ContentPlaceHolder id="CPH1" runat="server"></asp:ContentPlaceHolder></body></html>

The master page above is a normal HTML page designed as a template for other pages.

The @ Master directive defines it as a master page.

The master page contains a placeholder tag <asp:ContentPlaceHolder> for individual content.

The id="CPH1" attribute identifies the placeholder, allowing many placeholders in the same master page.

This master page was saved with the name "master1.master".

Note: The master page can also contain code, allowing dynamic content.

Content Page Example

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server"> <h2>Individual Content</h2> <p>Paragraph 1</p> <p>Paragraph 2</p></asp:Content>

The content page above is one of the individual content pages of the web.

The @ Page directive defines it as a standard content page.

The content page contains a content tag <asp:Content> with a reference to the master page (ContentPlaceHolderId="CPH1").

This content page was saved with the name "mypage1.aspx".

When the user requests this page, ASP.NET merges the content page with the master page.

Click to display mypage1.aspx.

Note: The content text must be inside the <asp:Content> tag. No content is allowed outside the tag.

Content Page With Controls

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server"> <h2>W3Schools</h2> <form runat="server"> <asp:TextBox id="textbox1" runat="server" /> <asp:Button id="button1" runat="server" text="Button" /> </form></asp:Content>

The content page above demonstrates how .NET controls can be inserted into the content page just like an into an ordinary page.

Click to display mypage2.aspx.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 203: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Navigation

ASP.NET has built-in navigation controls

Web Site NavigationMaintaining the menu of a large web site is difficult and time consuming.

In ASP.NET the menu can be stored in a file to make it easier to maintain. This file is normally called web.sitemap, and is stored in the root directory ofthe web.

In addition, ASP.NET has three new navigation controls:

Dynamic menusTreeViewsSite Map Path

The Sitemap FileThe following sitemap file is used in this tutorial:

<?xml version="1.0" encoding="ISO-8859-1" ?><siteMap> <siteMapNode title="Home" url="/aspnet/w3home.aspx"> <siteMapNode title="Services" url="/aspnet/w3services.aspx"> <siteMapNode title="Training" url="/aspnet/w3training.aspx"/> <siteMapNode title="Support" url="/aspnet/w3support.aspx"/> </siteMapNode> </siteMapNode></siteMap>

Rules for creating a sitemap file:

The XML file must contain a <siteMap> tag surrounding the contentThe <siteMap> tag can only have one <siteMapNode> child node (the "home" page)Each <siteMapNode> can have several child nodes (web pages)Each <siteMapNode> has attributes defining page title and URL

Note: The sitemap file must be placed in the root directory of the web and the URL attributes must be relative to the root directory.

Dynamic MenuThe <asp:Menu> control displays a standard site navigation menu.

Code Example:

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server"><asp:Menu runat="server" DataSourceId="nav1" /></form>

The <asp:Menu> control in the example above is a placeholder for a server created navigation menu.

The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control.

The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).

Click here to see a demo of Menu, TreeView, and SiteMapPath

TreeViewThe <asp:TreeView> control displays a multi level navigation menu.

The menu looks like a tree with branches that can be opened or closed with + or - symbol.

Code Example:

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server"><asp:TreeView runat="server" DataSourceId="nav1" /></form>

The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu.

The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control.

The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).

Click here to see a demo of Menu, TreeView, and SiteMapPath

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 204: ASP.Net

« Previous Next Chapter »

SiteMapPathThe SiteMapPath control displays the trail (navigation path) to the current page. The path acts as clickable links to previous pages.

Unlike the TreeView and Menu control the SiteMapPath control does NOT use a SiteMapDataSource. The SiteMapPath control uses the web.sitemap file bydefault.

Tips: If the SiteMapPath displays incorrectly, most likely there is an URL error (typo) in the web.sitemap file.

Code Example:

<form runat="server"><asp:SiteMapPath runat="server" /></form>

The <asp:SiteMapPath> control in the example above is a placeholder for a server created site path display.

Click here to see a demo of Menu, TreeView, and SiteMapPath

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 205: ASP.Net

« Previous Next Chapter »

« Previous Next Chapter »

ASP.NET Web Forms - HTML Controls

HTML server controls are HTML tags understood by the server.

HTML Server ControlsHTML elements in ASP.NET files are, by default, treated as text. To make these elementsprogrammable, add a runat="server" attribute to the HTML element. This attribute indicates that theelement should be treated as a server control.

Note: All HTML server controls must be within a <form> tag with the runat="server" attribute!

Note: ASP.NET requires that all HTML elements must be properly closed and properly nested.

HTML Server Control Description

HtmlAnchor Controls an <a> HTML element

HtmlButton Controls a <button> HTML element

HtmlForm Controls a <form> HTML element

HtmlGeneric Controls other HTML element not specified by a specific HTML servercontrol, like <body>, <div>, <span>, etc.

HtmlImage Controls an <image> HTML element

HtmlInputButton Controls <input type="button">, <input type="submit">, and <inputtype="reset"> HTML elements

HtmlInputCheckBox Controls an <input type="checkbox"> HTML element

HtmlInputFile Controls an <input type="file"> HTML element

HtmlInputHidden Controls an <input type="hidden"> HTML element

HtmlInputImage Controls an <input type="image"> HTML element

HtmlInputRadioButton Controls an <input type="radio"> HTML element

HtmlInputText Controls <input type="text"> and <input type="password"> HTMLelements

HtmlSelect Controls a <select> HTML element

HtmlTable Controls a <table> HTML element

HtmlTableCell Controls <td>and <th> HTML elements

HtmlTableRow Controls a <tr> HTML element

HtmlTextArea Controls a <textarea> HTML element

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 206: ASP.Net

ASP.NET HtmlAnchor Control

HTML Server Controls

Definition and UsageThe HtmlAnchor control is used to control an <a> element. In HTML, the <a> element is used tocreate a hyperlink. The hyperlink may link to a bookmark or to another Web page.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

HRef The URL target of the link

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Name The name of the anchor

OnServerClick The name of the function to be executed when the link is clicked

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Target The target window to open

Title A title to be displayed by the browser (like the title attribute of the imgelement)

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLAnchorDeclare two HtmlAnchor controls in an .aspx file (remember to embed the control inside an HtmlFormcontrol). Then modify the URL, target, and title of the HtmlAnchor controls in an event handler (anevent handler is a subroutine that executes code for a given event). The Page_Load event is one ofmany events that ASP .NET understands.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 207: ASP.Net

ASP.NET HtmlButton Control

HTML Server Controls

Definition and UsageThe HtmlButton control is used to control a <button> element. In HTML, the <button> element is used to create a push button.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are notautomatically converted to HTML entities

InnerText Sets or returns all text between the opening and closing tags of the HTML element. Special characters areautomatically converted to HTML entities

OnServerClick The name of the function to be executed when the button is clicked

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLButtonDeclare two HtmlButton controls in an .aspx file (remember to embed the control inside an HtmlForm control). Next, write an event handler that specifieswhat to happen when a button is clicked.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 208: ASP.Net

ASP.NET HtmlForm Control

HTML Server Controls

Definition and UsageThe HtmlForm control is used to control a <form> element. In HTML, the <form> element is used tocreate a form.

Note: All HTML server controls must be within the HtmlForm control!

Note: You can only have one HtmlForm control on a single page!

Properties

Property Description

Action A URL that defines where to send the data when the form is submitted.

Note: This attribute is always set to the URL of the page itself!

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

EncType The mime type used to encode the content of the form

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Method How the form posts data to the server. Legal values are: "post" and "get".Default is "post"

Name The name of the form

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Target The target window to load the URL

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLFormDeclare one HtmlInputText controls, one HtmlInputButton control, and one HtmlGeneric control in an.aspx file (remember to embed the controls inside an HtmlForm control). When the submit button istriggered, the submit subroutine is executed. The submit subroutine writes a welcome message to thep element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 209: ASP.Net

ASP.NET HtmlGeneric Control

HTML Server Controls

Definition and UsageThe HtmlGeneric control is used to control other HTML element not specified by a specific HTML server control, like <body>, <div>, <span>, <font>, <p>,etc.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are notautomatically converted to HTML entities

InnerText Sets or returns all text between the opening and closing tags of the HTML element. Special characters areautomatically converted to HTML entities

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLGenericDeclare one HtmlInputText controls, one HtmlInputButton control, and one HtmlGeneric control (the <p> tag) in an .aspx file (remember to embed thecontrols inside an HtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a welcomemessage to the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 210: ASP.Net

ASP.NET HtmlImage Control

HTML Server Controls

Definition and UsageThe HtmlImage control is used to control an <img> element. In HTML, the <img> element is used todisplay an image.

Properties

Property Description

Align How to align the image according to surrounding elements. Legal valuesare:

topmiddlebottomleftright

Alt A short description of the image

Attributes Returns all attribute name and value pairs of the element

Border The width of the borders around the image

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

Height The height of the image

id A unique id for the control

runat Specifies that the control is a server control. Must be set to "server"

Src The URL of the image to display

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Visible A Boolean value that indicates whether or not the control should be visible

Width The width of the image

ExamplesHTMLImageDeclare an HtmlImage control in an .aspx file (remember to embed the control inside an HtmlFormcontrol). Then we modify the src, alt and border properties of the HtmlImage control in an eventhandler (an event handler is a subroutine that executes code for a given event). The Page_Load eventis one of many events that ASP .NET understands:

HTMLImage 2Declare an HtmlImage and an HTMLSelect control in an .aspx file (remember to embed the controlsinside an HtmlForm control). Then we modify the src property of the HtmlImage control based on userchoices. The value selected in the HtmlSelect control determines which image to display.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 211: ASP.Net

ASP.NET HtmlInputButton Control

HTML Server Controls

Definition and UsageThe HtmlInputButton control is used to control <input type="button">, <input type="submit">, and <input type="reset"> elements. In HTML, theseelements are used to create a command button, a submit button, and a reset button.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

id A unique id for the element

Name The name of the element

OnServerClick The name of the function to be executed when the button is clicked

runat Specifies that the element is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLInputbuttonDeclare one HtmlInputText controls, one HtmlInputButton control, and one HtmlGeneric control in an .aspx file (remember to embed the controls inside anHtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a welcome message to the pelement.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 212: ASP.Net

ASP.NET HtmlInputCheckBox Control

HTML Server Controls

Definition and UsageThe HtmlInputCheckBox control is used to control an <input type="checkbox"> element. In HTML, thiselement is used to create a checkbox.

Properties and Events

Property Description

Attributes Returns all attribute name and value pairs of the element

Checked A Boolean value that specifies whether or not the element is to be checked

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the control

Name The name of the element

runat Specifies that the element is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

Event Description

ServerChange Occurs when the state of the control has changed

ExampleHTMLInputCheckboxDeclare two HtmlInputCheckBox controls, one HtmlInputButton control, and one HtmlGeneric in an.aspx file (remember to embed the controls inside an HtmlForm control). When the submit button istriggered, the submit subroutine is executed. The submit subroutine may respond in two ways: if the"red" checkbox is checked, the server sends the message "You prefer red!" to the p element. If the"blue" checkbox is checked, the server sends the message "You prefer blue!" to the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 213: ASP.Net

ASP.NET HtmlInputFile Control

HTML Server Controls

Definition and UsageThe HtmlInputFile control is used to control an <input type="file"> element. In HTML, this element isused to upload a file to the server.

Properties

Property Description

Accept List of acceptable MIME types

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the element

MaxLength The maximum number of characters allowed in this element

Name The name of the element

PostedFile Gets access to the posted file

runat Specifies that the element is a server control. Must be set to "server"

Size The width of the element

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

ExampleDeclare one HtmlInputFile control, one HtmlInputButton control, and three HtmlGeneric controls in an.aspx file (remember to embed the controls inside an HtmlForm control). When the submit button istriggered, the submit subroutine is executed. The file name and file type are displayed on the page,while the file itself is uploaded to the c directory on the server:

<script runat="server">Sub submit(Sender as Object, e as EventArgs) fname.InnerHtml=MyFile.PostedFile.FileName clength.InnerHtml=MyFile.PostedFile.ContentLength MyFile.PostedFile.SaveAs("c:\uploadfile.txt")End Sub</script>

<html><body>

<form method="post"enctype="multipart/form-data" runat="server"><p>Select file to upload to server:<input id="MyFile" type="file" size="40" runat="server"></p><p><input type="submit" value="Upload!" OnServerclick="submit"runat="server"></p><p><div runat="server"> FileName: <span id="fname" runat="server"/><br /> ContentLength: <span id="clength" runat="server"/> bytes</div></p></form>

</body></html>

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 214: ASP.Net

ASP.NET HtmlInputHidden Control

HTML Server Controls

Definition and UsageThe HtmlInputHidden control is used to control an <input type="hidden"> element. In HTML, this element is used to create a hidden input field.

Properties and Events

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

id A unique id for the element

Name The name of the element

runat Specifies that the element is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the hidden field

Visible A Boolean value that indicates whether or not the control should be visible

Event Description

ServerChange When the content of the element has changed

ExampleHTMLInputHiddenDeclare one HtmlInputHidden control, one HtmlInputText control, one HtmlInputButton control, and one HtmlGeneric control in an .aspx file (remember toembed the controls inside an HtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine sets thevalue of the hidden field equal to value of the input field and then displays the value of the hidden field in the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 215: ASP.Net

ASP.NET HtmlInputImage Control

HTML Server Controls

Definition and UsageThe HtmlInputImage control is used to control an <input type="image"> element. In HTML, thiselement is used to create an input button using an image, instead of a regular push-style button.

Properties and Events

Property Description

Align The alignment of the image

Alt An alternate text to display for the image

Attributes Returns all attribute name and value pairs of the element

Border The width of the borders around the element

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the control

Name The name of the element

OnServerClick The name of the function to be executed when the image is clicked

runat Specifies that the element is a server control. Must be set to "server"

Src The source of the image

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLInputImageDeclare two HtmlInputImage controls and one HtmlGeneric control in an .aspx file (remember to embedthe controls inside an HtmlForm control). If the user clicks on the first image, the button1 subroutine isexecuted. This subroutine sends the message "You clicked the smiley button!" to the p element. If theuser clicks on the second image, the button2 subroutine is executed. This subroutine sends themessage "You clicked the angry button!" to the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 216: ASP.Net

ASP.NET HtmlInputRadioButton Control

HTML Server Controls

Definition and UsageThe HtmlInputRadioButton control is used to control an <input type="radio"> element. In HTML, thiselement is used to create a radiobutton.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Checked A Boolean value that specifies whether or not the element is to be selected

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the element

Name The name of the radio button group

runat Specifies that the element is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLInputRadiobuttonDeclare three HtmlInputRadioButton controls, one HtmlInputButton control, and one HtmlGenericcontrol in an .aspx file (remember to embed the controls inside an HtmlForm control). When the submitbutton is triggered, the submit subroutine is executed. The submit subroutine may respond in threeways: if the radiobutton with id="r1" is selected, the server sends the message "Your favorite color isred" to the p element. If the radiobutton with id="r2" is selected, the server sends the message "Yourfavorite color is green" to the p element. If the radiobutton with id="r3" is selected, the server sendsthe message "Your favorite color is blue" to the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 217: ASP.Net

ASP.NET HtmlInputText Control

HTML Server Controls

Definition and UsageThe HtmlInputText control is used to control <input type="text"> and <input type="password"> elements. In HTML, these elements are used to create atext field and a password field.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

id A unique id for the element

MaxLength The maximum number of characters allowed in this element

Name The name of the element

runat Specifies that the element is a server control. Must be set to "server"

Size The width of the element

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Type The type of the element

Value The value of the element

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLInputTextDeclare one HtmlInputText controls, one HtmlInputButton control, and one HtmlGeneric control in an .aspx file (remember to embed the controls inside anHtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a welcome message to the pelement.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 218: ASP.Net

ASP.NET HtmlSelect Control

HTML Server Controls

Definition and UsageThe HtmlSelect control is used to control a <select> element. In HTML, the <select> element is usedto create a drop-down list.

Properties

Property Description

Attributes Returns all attribute name and value pairs of the element

DataMember A name of a data table to use

DataSource A data source to use

DataTextField A field in the data source to be displayed in the drop-down list

DataValueField A field in the data source that specifies the value of each selectable item inthe drop-down list

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Items The list of items in the drop-down list

Multiple Whether multiple items can be selected at a time

OnServerChange The name of the function to be executed when the selected item haschanged

runat Specifies that the control is a server control. Must be set to "server"

SelectedIndex The index of the currently selected item

Size The number of visible items in the drop-down list

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Value The value of the currently selected item

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLSelectDeclare an HtmlImage and an HTMLSelect control in an .aspx file (remember to embed the controlsinside an HtmlForm control). Then modify the src property of the HtmlImage control based on userchoices. The value selected in the HtmlSelect control determines which image to display.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 219: ASP.Net

ASP.NET HtmlTable Control

HTML Server Controls

Definition and UsageThe HtmlTable control is used to control a <table> element. In HTML, the <table> element is used tocreate a table.

Properties

Property Description

Align Specifies the alignment of the table

Attributes Returns all attribute name and value pairs of the element

BGColor Specifies the background color of the table

Border Specifies the width of the borders

Tip: Set border="0" to display tables with no borders!

BorderColor Specifies the color of the borders

CellPadding Specifies the space between the cell walls and contents

CellSpacing Specifies the space between cells

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

Height Specifies the height of the table

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Rows Returns an HtmlRowCollection object which represents all rows in the table

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Visible A Boolean value that indicates whether or not the control should be visible

Width Specifies the width of the table

ExamplesHTMLTableDeclare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspxfile (remember to embed the controls inside an HtmlForm control). The user may choose number ofcells and rows. When the submit button is triggered, the submit subroutine is executed. The submitsubroutine generates the table based on what the user did input.

HTMLTable 2Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed thecontrols inside an HtmlForm control). When the submit button is triggered, the submit subroutine isexecuted. The submit subroutine modifies the background color and the border color of the table, italso changes the contents of the cells.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 220: ASP.Net

ASP.NET HtmlTableCell Control

HTML Server Controls

Definition and UsageThe HtmlTableCell control is used to control <td> and <th> elements. In HTML, these elements areused to create table cells and header table cells.

Properties

Property Description

Align The horizontal alignment of cell content

Attributes Returns all attribute name and value pairs of the element

BGColor The background color of the cell

BorderColor The color of the borders

ColSpan The number of columns this cell should span

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

Height The height of the cell

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Nowrap A Boolean value that specifies whether or not the text within this controlshould wrap

RowSpan The number of rows this cell should span

runat Specifies that the control is a server control. Must be set to "server"

Style Gets the CSS properties that are applied to the control

TagName Returns the element tag name

VAlign The vertical alignment of cell content

Visible A Boolean value that indicates whether or not the control should be visible

Width The width of the cell

ExamplesHTMLTableDeclare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspxfile (remember to embed the controls inside an HtmlForm control). The user may choose number ofcells and rows. When the submit button is triggered, the submit subroutine is executed. The submitsubroutine generates the table based on what the user did input.

HTMLTable 2Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed thecontrols inside an HtmlForm control). When the submit button is triggered, the submit subroutine isexecuted. The submit subroutine modifies the background color and the border color of the table, italso changes the contents of the cells.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 221: ASP.Net

ASP.NET HtmlTableRow Control

HTML Server Controls

Definition and UsageThe HtmlTableRow control is used to control a <tr> element. In HTML, the <tr> element is used to create a table row.

Properties

Property Description

Align The alignment of the row

Attributes Returns all attribute name and value pairs of the element

BGColor The background color of the row

BorderColor The color of the borders

Cells Returns the cells in this row

Disabled A Boolean value that indicates whether or not the control should be disabled. Default is false

Height The height of the row

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are notautomatically converted to HTML entities

InnerText Sets or returns all text between the opening and closing tags of the HTML element. Special characters areautomatically converted to HTML entities

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

VAlign The vertical alignment of cells in the row

Visible A Boolean value that indicates whether or not the control should be visible

ExamplesHTMLTableDeclare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspx file (remember to embed the controls inside anHtmlForm control). The user may choose number of cells and rows. When the submit button is triggered, the submit subroutine is executed. The submitsubroutine generates the table based on what the user did input.

HTMLTable 2Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed the controls inside an HtmlForm control). When thesubmit button is triggered, the submit subroutine is executed. The submit subroutine modifies the background color and the border color of the table, it alsochanges the contents of the cells.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 222: ASP.Net

ASP.NET HtmlTextArea Control

HTML Server Controls

Definition and UsageThe HtmlTextArea control is used to control a <textarea> element. In HTML, the <textarea> elementis used to create a text area.

Properties and Events

Property Description

Attributes Returns all attribute name and value pairs of the element

Cols The number of columns of the text area

Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

id A unique id for the control

InnerHtml Sets or returns the content between the opening and closing tags of theHTML element. Special characters are not automatically converted to HTMLentities

InnerText Sets or returns all text between the opening and closing tags of the HTMLelement. Special characters are automatically converted to HTML entities

Name The unique name for the text area

OnServerChange The name of the function to be executed when the contents of the textareais changed

Rows The number of visible rows of the text area

runat Specifies that the control is a server control. Must be set to "server"

Style Sets or returns the CSS properties that are applied to the control

TagName Returns the element tag name

Value The content of the textarea

Visible A Boolean value that indicates whether or not the control should be visible

ExampleHTMLTextareaDeclare an HtmlTextarea control, an HtmlInputButton control, and an HtmlGeneric control in an .aspxfile (remember to embed the controls inside an HtmlForm control). When the submit button istriggered, the submit subroutine is executed. The submit subroutine sends the message "You wrote: "and the text the user wrote in the text area to the p element.

HTML Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 223: ASP.Net

ASP.NET AdRotator Control

Web Server Controls

Definition and UsageThe AdRotator control is used to display a sequence of ad images.

This control uses an XML file to store the ad information. The XML file must begin and end with an <Advertisements> tag. Inside the <Advertisements> tagthere may be several <Ad> tags which defines each ad.

The predefined elements inside the <Ad> tag are listed below:

Element Description

<ImageUrl> Optional. The path to the image file

<NavigateUrl> Optional. The URL to link to if the user clicks the ad

<AlternateText> Optional. An alternate text for the image

<Keyword> Optional. A category for the ad

<Impressions> Optional. The display rates in percent of the hits

Properties

Property Description .NET

AdvertisementFile Specifies the path to the XML file that contains ad information 1.0

AlternateTextField Specifies a data field to be used instead of the Alt text for an ad 2.0

ImageUrlField Specifies a data field to be used instead of the ImageURL attribute for an ad 2.0

KeywordFilter Specifies a filter to limit ads after categories 1.0

NavigateUrlField Specifies a data field to be used instead of the NavigateUrl attribute for an ad 2.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

Target Specifies where to open the URL 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Try it Yourself - Examples

AdRotatorDeclare an AdRotator control. Then we create an event handler for the AdCreated event, in the .aspx file, to override the value of the NavigateUrl element inthe XML file.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 224: ASP.Net

ASP.NET Button Control

Web Server Controls

Definition and UsageThe Button control is used to display a push button. The push button may be a submit button or acommand button. By default, this control is a submit button.

A submit button does not have a command name and it posts the Web page back to the server whenit is clicked. It is possible to write an event handler to control the actions performed when the submitbutton is clicked.

A command button has a command name and allows you to create multiple Button controls on a page.It is possible to write an event handler to control the actions performed when the command button isclicked.

Properties

Property Description .NET

CausesValidation Specifies if a page is validated when a button is clicked 1.0

CommandArgument Specifies additional information about the command to perform 1.0

CommandName Specifies the command associated with the Command event 1.0

OnClientClick Specifies the name of the function to be executed when a button isclicked

2.0

PostBackUrl Specifies the URL of the page to post to from the current page whena button is clicked

2.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

Text Specifies the text on a button 1.0

UseSubmitBehavior Specifies whether or not a button uses the browser's submitmechanism or the ASP.NET postback mechanism

2.0

ValidationGroup Specifies the group of controls a button causes validation, when itposts back to the server

2.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Try it Yourself - Examples

ButtonDeclare a submit Button control. Then create an event handler for the Click event which changes thetext on the button.

Button 2Declare a submit Button control. Then create an event handler for the Click event which changes thetext and the style of the button.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 225: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(Source As Object, e As EventArgs) button1.Text="You clicked me!"End Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:Button id="button1" Text="Click me!" runat="server"OnClick="submit" /></form>

</body></html>

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 226: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(Source As Object, e As EventArgs) button1.Style("background-color")="#0000ff" button1.Style("color")="#ffffff" button1.Style("width")="200px" button1.Style("cursor")="pointer" button1.Style("font-family")="verdana" button1.Style("font-weight")="bold" button1.Style("font-size")="14pt" button1.Text="You clicked me!"End Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:Button id="button1" Text="Click me!" runat="server"OnClick="submit" /></form>

</body></html>

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 227: ASP.Net

ASP.NET Calendar Control

Web Server Controls

Definition and UsageThe Calendar control is used to display a calendar in the browser.

This control displays a one-month calendar that allows the user to select dates and move to the nextand previous months.

Properties

Property Description .NET

Caption The caption of the calendar 2.0

CaptionAlign The alignment of the caption text 2.0

CellPadding The space, in pixels, between the cell walls and contents 1.0

CellSpacing The space, in pixels, between cells 1.0

DayHeaderStyle The style for displaying the names of the days 1.0

DayNameFormat The format for displaying the names of the days 1.0

DayStyle The style for displaying days 1.0

FirstDayOfWeek What should be the first day of week 1.0

NextMonthText The text displayed for the next month link 1.0

NextPrevFormat The format of the next and previous month links 1.0

NextPrevStyle The style for displaying next and previous month links 1.0

OtherMonthDayStyle The style for displaying days that are not in the current month 1.0

PrevMonthText The text displayed for the previous month link 1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

SelectedDate The selected date 1.0

SelectedDates The selected dates 1.0

SelectedDayStyle The style for selected days 1.0

SelectionMode How a user is allowed to select dates 1.0

SelectMonthText The text displayed for the month selection link 1.0

SelectorStyle The style for the month and weeks selection links 1.0

SelectWeekText The text displayed for the week selection link 1.0

ShowDayHeader A Boolean value that specifies whether the days of the weekheader should be shown

1.0

ShowGridLines A Boolean value that specifies whether the grid lines betweendays should be shown

1.0

ShowNextPrevMonth A Boolean value that specifies whether the next and previousmonth links should be shown

1.0

ShowTitle A Boolean value that specifies whether the title of the calendarshould be shown

1.0

TitleFormat The format for the title of the calendar 1.0

TitleStyle The style of the title of the calendar 1.0

TodayDayStyle The style for today's date 1.0

TodaysDate Today's date 1.0

UseAccessibleHeader Specifying whether to use the <th> element for the dayheaders instead of the <td> element

2.0

VisibleDate The date that specifies the month that is currently visible in thecalendar

1.0

WeekendDayStyle The style for weekends 1.0

OnDayRender The name of the function to be executed when when each daycell is created

OnSelectionChanged The name of the function to be executed when the user selectsa day, week, or month

OnVisibleMonthChanged The name of the function to be executed when the usernavigates to a different month

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 228: ASP.Net

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Try it Yourself - Examples

CalendarDeclare a Calendar control in its simplest use.

Calendar 2Declare a Calendar control where the days are displayed with full names in blue, the weekends aredisplayed in red on a yellow background, and the current date is displayed with a green background.

Calendar 3Declare a Calendar control where the days are displayed with full names, the user may select a day, aweek, or the whole month, and the selected day/week/month is displayed with a grey backgroundcolor.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 229: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:Calendar runat="server" /></form>

</body></html>

< July 2012 >Sun Mon Tue Wed Thu Fri Sat24 25 26 27 28 29 301 2 3 4 5 6 78 9 10 11 12 13 14

15 16 17 18 19 20 2122 23 24 25 26 27 2829 30 31 1 2 3 4

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 230: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:Calendar DayNameFormat="Full" runat="server"> <WeekendDayStyle BackColor="#fafad2" ForeColor="#ff0000"/> <DayHeaderStyle ForeColor="#0000ff" /> <TodayDayStyle BackColor="#00ff00" /></asp:Calendar></form>

</body></html>

< July 2012 >Sunday Monday Tuesday Wednesday Thursday Friday Saturday

24 25 26 27 28 29 301 2 3 4 5 6 78 9 10 11 12 13 1415 16 17 18 19 20 2122 23 24 25 26 27 2829 30 31 1 2 3 4

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 231: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:Calendar DayNameFormat="Full" runat="server"SelectionMode="DayWeekMonth"SelectMonthText="<*>"SelectWeekText="<->"/> <SelectorStyle BackColor="#f5f5f5" /></asp:Calendar></form>

</body></html>

< July 2012<*> Sunday Monday Tuesday Wednesday Thursday Friday Saturd<-> 24 25 26 27 28 29 30<-> 1 2 3 4 5 6 7<-> 8 9 10 11 12 13 14<-> 15 16 17 18 19 20 21<-> 22 23 24 25 26 27 28<-> 29 30 31 1 2 3 4

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 232: ASP.Net

ASP.NET Caption Property

Complete Calendar Control Reference

Definition and UsageThe Caption property is used to get or set a text that is shown as a caption for the calendar.

Syntax

<asp:Calendar Caption="text" runat="server" />

Attribute Description

text The text to be shown as the calendars caption

Example

The following example sets the Caption property in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"Caption="This is a Caption text" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 233: ASP.Net

ASP.NET CaptionAlign Property

Complete Calendar Control Reference

Definition and UsageThe CaptionAlign property is used to get or set the alignment of the caption text for a calendar.

Syntax

<asp:Calendar Caption="text" CaptionAlign="align" runat="server" />

Attribute Description

align Specifies the alignment of the caption text

Possible Values:

Top - Caption is displayed at the top of the calendar. Text is centeredBottom - Caption is displayed at the bottom of the calendar. Text is centeredLeft - Caption is displayed at the top of the calendar. Text is left-alignedRight - Caption is displayed at the top of the calendar. Text is right-aligned

Example

The following example sets the Caption property in a calendar and aligns it to the bottom of thecalendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"Caption="This is a Caption text"CaptionAlign="bottom" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 234: ASP.Net

ASP.NET CellPadding Property

Complete Calendar Control Reference

Definition and UsageThe CellPadding property is used to sets the space between the border and the contents of a calendarcell.

Syntax

<asp:Calendar CellPadding="pixels" runat="server" />

Attribute Description

pixels Specifies the space (in pixels) between the border and the contents of a calendarcell

Example

The following example shows a calendar with CellPadding 15:

<form runat="server"><asp:Calendar id="cal1" runat="server" CellPadding="15" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 235: ASP.Net

ASP.NET CellSpacing Property

Complete Calendar Control Reference

Definition and UsageThe CellSpacing property is used to sets the space between calendar cells.

Note: This property does not display properly in FireFox browsers.

Syntax

<asp:Calendar CellSpacing="pixels" runat="server" />

Attribute Description

pixels Specifies the space (in pixels) between calendar cells

Example

The following example shows a calendar with CellSpacing 15:

<form runat="server"><asp:Calendar id="cal1" runat="server" CellSpacing="15" /></form>

Show example »

Complete Calendar Control Referenc

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 236: ASP.Net

ASP.NET DayHeaderStyle Property

Complete Calendar Control Reference

Definition and UsageThe DayHeaderStyle property is used to set or return the style of the weekday header in the calendar.

Syntax

<asp:Calendar runat="server"><DayHeaderStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" DayHeaderStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the DayHeaderStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><DayHeaderStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the DayHeaderStyle in a calendar:

<form runat="server"> <asp:Calendar id="cal2" runat="server" DayHeaderStyle-ForeColor="#FF0000" /> </form>

Try-It-Yourself DemosSet DayHeaderStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 237: ASP.Net

ASP.NET DayNameFormat Property

Complete Calendar Control Reference

Definition and UsageThe DayNameFormat property is used to set the format of the weekday names in the calendar.

Syntax

<asp:Calendar DayNameFormat="format" runat="server" />

Attribute Description

format Specifies the format for displaying the names of the days.

Possible values:

FirstLetterFirstTwoLettersFullShort

Example

The following example shows a calendar with the full day name format:

<form runat="server"><asp:Calendar id="cal1" runat="server" DayNameFormat="Full" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 238: ASP.Net

ASP.NET DayStyle Property

Complete Calendar Control Reference

Definition and UsageThe DayStyle property is used to set or return the style of the days in the calendar.

Syntax

<asp:Calendar runat="server"><DayStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" DayStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the DayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><DayStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the DayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"DayStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet DayStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 239: ASP.Net

ASP.NET FirstDayOfWeek Property

Complete Calendar Control Reference

Definition and UsageThe FirstDayOfWeek property is used to specify what day should be the first day of the week in thecalendar.

Syntax

<asp:Calendar FirstDayOfWeek="day" runat="server" />

Attribute Description

day Specifies the first day of the week in the calendar.

Possible values:

DefaultMondayTuesdayWednesdayThursdayFridaySaturdaySunday

Example

The following example shows a calendar with Wednesday set as the first day of the week:

<form runat="server"><asp:Calendar id="cal1" runat="server" FirstDayOfWeek="Wednesday" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 240: ASP.Net

ASP.NET NextMonthText Property

Complete Calendar Control Reference

Definition and UsageThe NextMonthText property is used to specify the text displayed for the next month link in a calendar.

Syntax

<asp:Calendar NextMonthText="string" runat="server" />

Attribute Description

string Specifies the text displayed for the next month link in the calendar. The defaultvalue is ">"

Example

The following example shows a calendar with the NextMonthText set to "Next":

<form runat="server"><asp:Calendar id="cal1" runat="server" NextMonthText="Next" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 241: ASP.Net

ASP.NET NextPrevFormat Property

Complete Calendar Control Reference

Definition and UsageThe NextPrevFormat property is used to specify the format of the Next and Previous month links in thecalendar.

Syntax

<asp:Calendar NextPrevFormat="format" runat="server" />

Attribute Description

format Specifies the format of the next and previous month links in the calendar.

Possible values:

ShortMonthFullMonthCustomText

Example

The following example shows a calendar with the NextPrevFormat set to "ShortMonth":

<form runat="server"><asp:Calendar id="cal1" runat="server" NextPrevFormat="ShortMonth" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 242: ASP.Net

ASP.NET NextPrevStyle Property

Complete Calendar Control Reference

Definition and UsageThe NextPrevStyle property is used to set or return the style of the Next and Previous month links inthe calendar.

Syntax

<asp:Calendar runat="server"><NextPrevStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" NextPrevStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the NextPrevStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><NextPrevStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the NextPrevStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"NextPrevStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet NextPrevStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 243: ASP.Net

ASP.NET OtherMonthDayStyle Property

Complete Calendar Control Reference

Definition and UsageThe OtherMonthDayStyle property is used to set or return the style of the days in the calendar that arenot part of the current month.

Syntax

<asp:Calendar runat="server"><OtherMonthDayStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" OtherMonthDayStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the OtherMonthDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><OtherMonthDayStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the OtherMonthDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"OtherMonthDayStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet OtherMonthDayStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 244: ASP.Net

ASP.NET PrevMonthText Property

Complete Calendar Control Reference

Definition and UsageThe PrevMonthText property is used to specify the text displayed for the previous month link in acalendar.

Syntax

<asp:Calendar PrevMonthText="string" runat="server" />

Attribute Description

string Specifies the text displayed for the previous month link in the calendar. Thedefault value is "<"

Example

The following example shows a calendar with the PrevMonthText set to "Prev":

<form runat="server"><asp:Calendar id="cal1" runat="server" PrevMonthText="Prev" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 245: ASP.Net

ASP.NET SelectedDate Property

Complete Calendar Control Reference

Definition and UsageThe SelectedDate property is used to get or set the selected date on a calendar.

Example

The following example outputs the selected date when a date is selected:

<script language="VB" runat="server">Sub Change(obj As Object, e As EventArgs) Response.Write("Date: ") Response.Write(cal1.SelectedDate.ToShortDateString())End Sub</script>

<form runat="server"><asp:Calendar id="cal1" runat="server"OnSelectionChanged="Change" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 246: ASP.Net

ASP.NET SelectedDates Property

Complete Calendar Control Reference

Definition and UsageThe SelectedDates property is used to get or set the selected dates from a calendar.

Example

The following example outputs the selected dates when a date is selected:

<script language="VB" runat="server">Sub Change(obj As Object, e As EventArgs) Dim i As Integer For i = 0 To Cal1.SelectedDates.Count - 1 Response.Write(Cal1.SelectedDates(i).ToShortDateString()) Response.Write("<br />") Next iEnd Sub</script>

<form runat="server"><asp:Calendar id="cal1" runat="server"SelectionMode="DayWeekMonth"OnSelectionChanged="Change" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 247: ASP.Net

ASP.NET SelectedDayStyle Property

Complete Calendar Control Reference

Definition and UsageThe SelectedDayStyle property is used to set or return the style of the selected days in the calendar.

Syntax

<asp:Calendar runat="server"><SelectedDayStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" SelectedDayStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the SelectedDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><SelectedDayStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the SelectedDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"SelectedDayStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet SelectedDayStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 248: ASP.Net

ASP.NET SelectionMode Property

Complete Calendar Control Reference

Definition and UsageThe SelectionMode property is used to get or set how a user is allowed to select dates.

Syntax

<asp:Calendar SelectionMode="mode" runat="server" />

Attribute Description

mode Specifies how a users is allowed to select dates.

Possible values:

NoneDayDayWeekDayWeekMonth

Example

The following example sets the SelectionMode of a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"SelectionMode="DayWeekMonth" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 249: ASP.Net

ASP.NET SelectMonthText Property

Complete Calendar Control Reference

Definition and UsageThe SelectMonthText property is used to specify the text for selecting an entire month in a calendar.

Note: This property only works when the SelectionMode property is set to DayWeekMonth.

Syntax

<asp:Calendar SelectMonthText="string" runat="server" />

Attribute Description

string Specifies the text displayed for selecting an entire month in a calendar. Thedefault value is ">>"

Example

The following example shows a calendar with the SelectMonthText set to "->":

<form runat="server"><asp:Calendar id="cal1" runat="server"SelectMonthText="->" SelectionMode="DayWeekMonth" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 250: ASP.Net

ASP.NET SelectorStyle Property

Complete Calendar Control Reference

Definition and UsageThe SelectorStyle property is used to set or return the style week and month selectors.

Syntax

<asp:Calendar runat="server"><SelectorStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" SelectorStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the SelectorStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><SelectorStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the SelectorStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"SelectorStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet SelectorStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 251: ASP.Net

ASP.NET SelectWeekText Property

Complete Calendar Control Reference

Definition and UsageThe SelectWeekText property is used to specify the text for selecting an entire week in a calendar.

Note: This property only works when the SelectionMode property is set to DayWeek or DayWeekMonth.

Syntax

<asp:Calendar SelectWeekText="string" runat="server" />

Attribute Description

string Specifies the text displayed for selecting an entire week in a calendar. The default value is ">>"

Example

The following example shows a calendar with the SelectWeekText set to "->":

<form runat="server"><asp:Calendar id="cal1" runat="server"SelectWeekText="->" SelectionMode="DayWeek" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 252: ASP.Net

ASP.NET ShowDayHeader Property

Complete Calendar Control Reference

Definition and UsageThe ShowDayHeader property is used to specify whether or not to display the names of the weekdays in the calendar.

By default this property is set as TRUE and the weekday names are displayed. To remove the weekday names the property must be set as FALSE.

Syntax

<asp:Calendar ShowDayHeader="TRUE|FALSE" runat="server" />

Example

The following example sets the ShowDayHeader as FALSE:

<form runat="server"><asp:Calendar id="cal1" runat="server"ShowDayHeader="FALSE" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 253: ASP.Net

ASP.NET ShowGridLines Property

Complete Calendar Control Reference

Definition and UsageThe ShowGridLines property is used to specify whether or not to display borders between the days inthe calendar.

By default this property is set as FALSE and the grid lines are not displayed. To show the grid lines theproperty must be set as TRUE.

Syntax

<asp:Calendar ShowGridLines="TRUE|FALSE" runat="server" />

Example

The following example sets the ShowGridLines as TRUE:

<form runat="server"><asp:Calendar id="cal1" runat="server"ShowGridLines="TRUE" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 254: ASP.Net

ASP.NET ShowNextPrevMonth Property

Complete Calendar Control Reference

Definition and UsageThe ShowNextPrevMonth property is used to specify whether or not to display the next and previous month links in the calendar.

By default this property is set as TRUE and the next and previous month links are displayed. To remove the links the property must be set as FALSE.

Syntax

<asp:Calendar ShowNextPrevMonth="TRUE|FALSE" runat="server" />

Example

The following example sets the ShowNextPrevMonth as FALSE:

<form runat="server"><asp:Calendar id="cal1" runat="server"ShowNextPrevMonth="FALSE" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 255: ASP.Net

ASP.NET ShowTitle Property

Complete Calendar Control Reference

Definition and UsageThe ShowTitle property is used to specify whether or not to display the title in the calendar.

By default this property is set as TRUE and the calendar title are displayed. To remove the title the property must be set as FALSE.

Note: Hiding the title hides the name of the month and the next and previous month links

Syntax

<asp:Calendar ShowTitle="TRUE|FALSE" runat="server" />

Example

The following example sets the ShowTitle as FALSE:

<form runat="server"><asp:Calendar id="cal1" runat="server"ShowTitle="FALSE" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 256: ASP.Net

ASP.NET TitleFormat Property

Complete Calendar Control Reference

Definition and UsageThe TitleFormat property is used to get or set how the title of a calendar is displayed.

Syntax

<asp:Calendar TitleFormat="mode" runat="server" />

Attribute Description

mode Specifies how the calendar title is shown

Possible values:

MonthMonthYear (Default)

Example

The following example sets the TitleFormat to display month:

<form runat="server"><asp:Calendar id="cal1" runat="server"TitleFormat="Month" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 257: ASP.Net

ASP.NET TitleStyle Property

Complete Calendar Control Reference

Definition and UsageThe TitleStyle property is used to set or return the style of the title of a calendar.

Syntax

<asp:Calendar runat="server"><TitleStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" TitleStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the TitleStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><TitleStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the TitleStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"TitleStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet TitleStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 258: ASP.Net

ASP.NET TodayDayStyle Property

Complete Calendar Control Reference

Definition and UsageThe TodayDayStyle property is used to set or return the style of the current date in a calendar.

Syntax

<asp:Calendar runat="server"><TodayDayStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" TodayDayStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles andtheir values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the TodayDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><TodayDayStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the TodayDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"TodayDayStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet TodayDayStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 259: ASP.Net

ASP.NET TodaysDate Property

Complete Calendar Control Reference

Definition and UsageThe TodaysDate property is used to get or set the current date from a calendar.

If this property is not set, this date will be the date on the server.

Example

The following example shows a outputs today's date:

<script language="VB" runat="server">Sub Page_Load Response.Write("Today is: ") Response.Write(cal1.TodaysDate.ToShortDateString())End Sub</script>

<form runat="server"><asp:Calendar id="cal1" runat="server" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 260: ASP.Net

ASP.NET VisibleDate Property

Complete Calendar Control Reference

Definition and UsageThe VisibleDate property is used to get or set the date that specifies the month to display in the calendar.

Example

The following example sets the VisibleDate to 01-Oct-07:

<script runat="server">Sub Page_Load cal1.VisibleDate = DateValue("01-Oct-07")End Sub</script>

<form runat="server"> <asp:Calendar id="cal1" runat="server" /></form>

Show example »

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 261: ASP.Net

ASP.NET WeekendDayStyle Property

Complete Calendar Control Reference

Definition and UsageThe WeekendDayStyle property is used to set or return the style of the weekends in a calendar.

Syntax

<asp:Calendar runat="server"><WeekendDayStyle style="value" /></asp:Calendar>

or

<asp:Calendar runat="server" WeekendDayStyle-style="value" />

Attribute Description

style Specifies the style to set. See the Style Control to see the possible styles and their values

value Specifies the value of the specified style

Example 1

The following example shows one way to set the WeekendDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal1" runat="server"><WeekendDayStyle ForeColor="#FF0000" /></asp:Calendar></form>

Show example »

Example 2The following example shows another way to set the WeekendDayStyle in a calendar:

<form runat="server"><asp:Calendar id="cal2" runat="server"WeekendDayStyle-ForeColor="#FF0000" /></form>

Try-It-Yourself DemosSet WeekendDayStyle of a Calendar control (with declaration and script)

Complete Calendar Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 262: ASP.Net

ASP.NET CalendarDay Control

Web Server Controls

Definition and UsageThe CalendarDay control represents a day in a calendar control.

Properties

Property Description .NET

Date The date variable of the date 1.0

DayNumberText The day number(string) of a date 1.0

IsOtherMonth Specifies if the date in another month than the one displayed inthe calendar

1.0

IsSelectable Specifies if the date is selectable 1.0

IsSelected Specifies if the date is selected 1.0

IsToday Specifies if the date is today's date 1.0

IsWeekend Specifies if the date is Saturday or Sunday 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 263: ASP.Net

ASP.NET Date Property

Complete CalendarDay Control Reference

Definition and UsageThe Date property is used to get a date variable representing the date.

Example

The following example shows how to get the Date from a selected day in a calendar:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then Label1.Text = e.Day.Date End IfEnd Sub</script>

<form runat="server"><asp:Calendar id="cal1" runat="server"OnDayRender="DaySelect" />The selected date is:<asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 264: ASP.Net

ASP.NET DayNumberText Property

Complete CalendarDay Control Reference

Definition and UsageThe DayNumberText property is used to get a string representing the day number of a date.

Example

The following example shows how to get the DayNumberText from a selected day in a calendar:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then Label1.Text = e.Day.DayNumberText End IfEnd Sub</script>

<form runat="server"><asp:Calendar id="cal1" runat="server"OnDayRender="DaySelect" />The selected date is:<asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 265: ASP.Net

ASP.NET IsOtherMonth Property

Complete CalendarDay Control Reference

Definition and UsageThe IsOtherMonth property is used to get whether or not the date is in the month displayed by the calendar.

This property returns "FALSE" if the date is the displayed month.

Example

The following example shows if the selected day is in the current month or not:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then If e.Day.IsOtherMonth = "TRUE" Then Label1.Text = "NO" Else Label1.Text = "YES" End If End IfEnd Subv </script>

<form runat="server"> <asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect"/> The selected date is in the current month: <asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 266: ASP.Net

ASP.NET IsSelectable Property

Complete CalendarDay Control Reference

Definition and UsageThe IsSelectable property is used to get or set whether or not a date is selectable.

This property returns "TRUE" if the date is selectable.

Example

The following example shows a calendar where the weekends are not selectable:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsWeekend Then e.Day.IsSelectable = False End IfEnd Sub</script>

<form runat="server"> <form runat="server"> The weekends are not selectable <asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect" /></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 267: ASP.Net

ASP.NET IsSelected Property

Complete CalendarDay Control Reference

Definition and UsageThe IsSelected property is used to get whether or not a date is selected in a calendar control.

This property returns "TRUE" if the date is selected.

Example

The following example shows if the selected day is in the current month or not:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then If e.Day.IsOtherMonth = "TRUE" Then Label1.Text = "NO" Else Label1.Text = "YES" End If End IfEnd Sub</script>

<form runat="server"> <asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect"/> The selected date is in the current month: <asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 268: ASP.Net

ASP.NET IsToday Property

Complete CalendarDay Control Reference

Definition and UsageThe IsToday property is used to get whether or not the date is the current date.

This property returns "TRUE" if the date is the current date.

Example

The following example shows if the selected day is the current date or not:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then If e.Day.IsToday = "TRUE" Then Label1.Text = "YES" Else Label1.Text = "NO" End If End IfEnd Sub</script>

<form runat="server"> <asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect" /> The selected date is in the current month: <asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 269: ASP.Net

ASP.NET IsWeekend Property

Complete CalendarDay Control Reference

Definition and UsageThe IsWeekend property is used to get whether or not the date is a Saturday or Sunday.

This property returns "TRUE" if the date is in a weekend.

Example

The following example shows if the selected day is in a weekend or not:

<script runat="server">Sub DaySelect(obj As Object, e As DayRenderEventArgs) If e.Day.IsSelected Then If e.Day.IsWeekend = "TRUE" Then Label1.Text = "YES" Else Label1.Text = "NO" End If End IfEnd Sub</script>

<form runat="server"> <asp:Calendar id="cal1" runat="server" OnDayRender="DaySelect"/> The selected date is in a weekend: <asp:Label id="Label1" runat="server"/></form>

Show example »

Complete CalendarDay Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 270: ASP.Net

ASP.NET DropDownList Control

Web Server Controls

Definition and UsageThe DropDownList control is used to create a drop-down list.

Each selectable item in a DropDownList control is defined by a ListItem element!

Tip: This control supports data binding!

Properties

Property Description .NET

SelectedIndex The index of a selected item 1.0

OnSelectedIndexChanged The name of the function to be executed when the index of theselected item has changed

1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

ListControl Standard Properties

AppendDataBoundItems, AutoPostBack, CausesValidation, DataTextField,DataTextFormatString, DataValueField, Items, runat, SelectedIndex,SelectedItem, SelectedValue, TagKey, Text, ValidationGroup,OnSelectedIndexChanged

The ListControl control covers all the base functions for list controls. Controls that inherits from thiscontrol include the CheckBoxList, DropDownList, ListBox, and RadioButtonList controls.

For a full description, go to ListControl Standard Attributes.

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleDropdownListDeclare one DropDownList control in an .aspx file. Then create an event handler for the Click eventwhich displays some text and the selected item, in a Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 271: ASP.Net

ASP.NET SelectedIndex Property

Complete DropDownList Control Reference

Definition and UsageThe SelectedIndex property is used to get or set the index number of the selected item in aDropDownList.

Example

The following example outputs the text of the selected item:

<script runat="Server">Sub GetName(obj As Object, e As EventArgs) lbl.Text = ddList.SelectedItem.TextEnd Sub</script>

<form runat="Server">Select a name from the list:<asp:DropDownList id="ddList" runat="Server"> <asp:ListItem Text="Peter" /> <asp:ListItem Text="Lois" /> <asp:ListItem Text="Cleveland" /> <asp:ListItem Text="Quagmire" /> <asp:ListItem Text="Joe" /></asp:DropDownList>

<asp:Button Text="Select"OnClick="GetName" Runat="Server" /><br />Name is:<asp:Label id="lbl" Runat="Server"/></form>

Show example »

Complete DropDownList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 272: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(sender As Object, e As EventArgs) mess.Text="You selected " & drop1.SelectedItem.TextEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:DropDownList id="drop1" runat="server"><asp:ListItem>Item 1</asp:ListItem><asp:ListItem>Item 2</asp:ListItem><asp:ListItem>Item 3</asp:ListItem><asp:ListItem>Item 4</asp:ListItem><asp:ListItem>Item 5</asp:ListItem><asp:ListItem>Item 6</asp:ListItem></asp:DropDownList><asp:Button Text="Submit" OnClick="submit" runat="server"/><p><asp:label id="mess" runat="server"/></p></form>

</body></html>

Item 1

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 273: ASP.Net

ASP.NET HyperLink Control

Web Server Controls

Definition and UsageThe HyperLink control is used to create a hyperlink.

Properties

Property Description .NET

ImageUrl The URL of the image to display for the link 1.0

NavigateUrl The target URL of the link 1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

Target The target frame of the URL 1.0

Text The text to display for the link 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleHyperlinkDeclare a HyperLink control in an .aspx file.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 274: ASP.Net

ASP.NET ImageUrl Property

Complete HyperLink Control Reference

Definition and UsageThe ImageUrl property is used to set or return the URL of an image to display for the hyperlink.

Syntax

<asp:HyperLink ImageUrl="URL" runat="server" />

Attribute Description

URL The URL of the image to use

Example

The following example sets the ImageUrl on a HyperLink control:

<form runat="server"><asp:HyperLink id="link1" runat="server"NavigateUrl="http://www.w3schools.com" ImageUrl="img.gif" /></form>

Show example »

Complete HyperLink Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 275: ASP.Net

ASP.NET NavigateUrl Property

Complete HyperLink Control Reference

Definition and UsageThe NavigateURL property is used to set or return the URL of a HyperLink control.

Syntax

<asp:HyperLink NavigateUrl="URL" runat="server" />

Attribute Description

URL A string that specifies the URL of the hyperlink control

Example

The following example sets the URL of a HyperLink control:

<form runat="server"><asp:HyperLink id="link1" runat="server" Text="W3Schools"NavigateUrl="http://www.w3schools.com" /></form>

Show example »

Complete HyperLink Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 276: ASP.Net

ASP.NET Target Property

Complete HyperLink Control Reference

Definition and UsageThe Target property is used to set or return the target of a HyperLink control.

Syntax

<asp:HyperLink Target="target" runat="server" />

Attribute Description

target Where to open the target URL.

_blank - the target URL will open in a new window_self - the target URL will open in the same frame as it was clicked_parent - the target URL will open in the parent frameset_top - the target URL will open in the full body of the window

Example

The following example sets the Target on a HyperLink control:

<form runat="server"><asp:HyperLink id="link1" runat="server" Text="W3Schools"NavigateUrl="http://www.w3schools.com" Target="_blank" /></form>

Show example »

Complete HyperLink Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 277: ASP.Net

ASP.NET Text Property

Complete HyperLink Control Reference

Definition and UsageThe Text property is used to set or return the text of a HyperLink control.

Syntax

<asp:HyperLink Text="string" runat="server" />

Attribute Description

string A string that specifies the text on the hyperlink control

Example

The following example sets the text on a HyperLink control:

<form runat="server"><asp:HyperLink id="link1" runat="server" Text="W3Schools"NavigateUrl="http://www.w3schools.com" /></form>

Show example »

Complete HyperLink Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 278: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:HyperLinkImageUrl="/banners/w6.gif"NavigateUrl="http://www.w3schools.com"Text="Visit W3Schools!"Target="_blank"runat="server" /></form>

</body></html>

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 279: ASP.Net

ASP.NET Image Control

Web Server Controls

Definition and UsageThe Image control is used to display an image.

Properties

Property Description .NET

AlternateText An alternate text for the image 1.0

DescriptionUrl The location to a detailed description for the image 2.0

GenerateEmptyAlternateText Specifies whether or not the control creates an empty string as analternate text

2.0

ImageAlign Specifies the alignment of the image 1.0

ImageUrl The URL of the image to display for the link 1.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth, CssClass,Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID, Style, TabIndex,

ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,

TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleImage

Declare an Image control in an .aspx file.

Web Server Controls

WEB HOSTING

Best Web Hosting

PHP MySQL Hosting

Best Hosting Coupons

UK Reseller Hosting

Cloud Hosting

Top Web Hosting

$3.98 Unlimited Hosting

Premium Website Design

WEB BUILDING

Download XML Editor

FREE Website BUILDER

Build a FREE Website

W3SCHOOLS EXAMS

Get Certified in:HTML, CSS, JavaScript,

XML, PHP, and ASP

W3SCHOOLS BOOKS

New Books:HTML, CSS

JavaScript, and Ajax

STATISTICS

Browser StatisticsBrowser OS

Browser Display

SHARE THIS PAGE

Share with »

REPORT ERROR | HOME | TOP | PRINT | FORUM | ABOUT

W3Schools is optimized for learning, testing,

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 280: ASP.Net

ASP.NET AlternateText Property

Complete Image Control Reference

Definition and UsageThe AlternateText property is used to set or return the alternate text of an image.

This property specifies the text to display if the image is not available.

The alternate text displays as a ToolTip if your browser supports it (Internet Explorer)

Syntax

<asp:Image AlternateText="text" runat="server" />

Attribute Description

text Specifies an alternate text for the image

Example

The following example sets the AlternateText for an Image control (image file does not exist):

<form runat="server"><asp:Image id="Img1" ImageUrl="missing_img.gif"runat="server" AlternateText="Image Text" /></form>

Show example »

Complete Image Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 281: ASP.Net

ASP.NET ImageAlign Property

Complete Image Control Reference

Definition and UsageThe ImageAlign property is used to set or return the alignment of the image.

Syntax

<asp:Image ImageAlign="align" runat="server" />

Attribute Description

align Specifies the alignment of the image.

Possible values:

NotSetAbsBottomAbsMiddleBaseLineBottomLeftMiddleRightTextTopTop

Example

The following example sets the ImageAlign for an Image control:

<form runat="server"><asp:Image id="Img1" runat="server"ImageUrl="img.gif" ImageAlign="Right" /></form>

Show example »

Complete Image Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 282: ASP.Net

ASP.NET ImageUrl Property

Complete Image Control Reference

Definition and UsageThe ImageUrl property is used to set or return the URL of an image to display.

Syntax

<asp:Image ImageUrl="URL" runat="server" />

Attribute Description

URL The URL of the image to use

Example

The following example sets the ImageUrl for an Image control:

<form runat="server"><asp:Image id="Img1" runat="server" ImageUrl="img.gif" /></form>

Show example »

Complete Image Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 283: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:Imagerunat="server"AlternateText="W3Schools"ImageUrl="/banners/w6.gif"/></form>

</body></html>

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 284: ASP.Net

ASP.NET ImageButton Control

Web Server Controls

Definition and UsageThe ImageButton control is used to display a clickable image.

Properties

Property Description .NET

CausesValidation Specifies if a page is validated when an ImageButton control isclicked

1.0

CommandArgument Additional information about the command to perform 1.0

CommandName The command associated with the Command event 1.0

GenerateEmptyAlternateText Specifies whether or not the control creates an empty string asan alternate text

2.0

OnClientClick The name of the function to be executed when the image isclicked

2.0

PostBackUrl The URL of the page to post to from the current page when theImageButton control is clicked

2.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

TagKey 1.0

ValidationGroup The group of controls for which the ImageButton control causesvalidation when it posts back to the server

2.0

Note: The properties of the Image control can also be used on the ImageButton control.

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleImageButtonDeclare one ImageButton control and one Label control in an .aspx file. When the user clicks on theimage, the getCoordinates subroutine is executed. The subroutine sends the message "Coordinates: "and the x and y coordinates of the click to the Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 285: ASP.Net

ASP.NET CausesValidation Property

Complete ImageButton Control Reference

Definition and UsageThe CausesValidation property specifies if a page is validated when a ImageButton control is clicked.

Page validation is performed when a button is clicked by default.

This property is mostly used to prevent validation when a cancel or reset button is clicked.

Syntax

<asp:ImageButton CausesValidation="TRUE|FALSE" runat="server" />

Example

The following example removes validation when an ImageButton is clicked:

<form runat="server"><asp:ImageButton id="button1" runat="server"CausesValidation="FALSE" ImageUrl="img.gif" /></form>

Show example »

Complete ImageButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 286: ASP.Net

ASP.NET ValidationGroup Property

Complete ImageButton Control Reference

Definition and UsageThe OnClientClick property is used to sets a client side script to be run when the ImageButton control is clicked.

The script specified in this property is run by the ImageButton's event "OnClick" in addition to the predefined script.

Syntax

<asp:ImageButton OnClientClick="func" runat="server" />

Attribute Description

func Client side script to be run when ImageButton is clicked

Example

The following example runs two scripts when the ImageButton control is clicked:

<script runat="server">Sub script1(obj As Object, e As ImageClickEventArgs) lblMsg.Text="Hello!"End Sub</script>

<form runat="server"><asp:ImageButton OnClick="script1" OnClientClick="script2()"ImageUrl="img.gif" runat="server" /><br /><asp:label id="lblMsg" runat="server" /></form>

<script type="text/javascript">function script2() { return confirm('Hello!'); }</script>

Show example »

Complete ImageButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 287: ASP.Net

ASP.NET PostBackUrl Property

Complete ImageButton Control Reference

Definition and UsageThe PostBackUrl property is used to gets or sets the URL of the page to post when the ImageButtoncontrol is clicked.

Syntax

<asp:ImageButton PostBackUrl="string" runat="server" />

Attribute Description

string String specifying the URL of the page to post to. Default is an empty string, thiscauses the page to post back to itself

Example

The following example sets the post URL of a ImageButton control:

<form runat="server"> Name:<asp:textbox id="TextBox1" runat=Server /> <asp:ImageButton id="Button1" ImageUrl="img.gif" PostBackUrl="demo_postbackurl.aspx" runat="Server" /></form>

Show example »

Complete ImageButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 288: ASP.Net

ASP.NET ValidationGroup Property

Complete ImageButton Control Reference

Definition and UsageThe ValidationGroup property specifies which group of controls is validated on validation.

This property is mostly used when there are several buttons in a form.

Syntax

<asp:ImageButton ValidationGroup="group" runat="server" />

Attribute Description

group The validation group to validate.

Example

The following example validates the specific validation group:

<asp:textbox id="tb1" runat=Server /><asp:requiredfieldvalidator id="ReqField1" controltovalidate="tb1"validationgroup="valGroup1" errormessage="Required" runat=Server />

<asp:ImageButton id="Button2" causesvalidation=truevalidationgroup="valGroup2" ImageUrl="img.gif" runat=Server />

Show example »

Complete ImageButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 289: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub getCoordinates(sender As Object, e As ImageClickEventArgs) mess.Text="Coordinates: " & e.x & ", " & e.yEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><p>Click on the image:</p><asp:ImageButtonrunat="server"ImageUrl="smiley.gif"OnClick="getCoordinates"/><p><asp:label id="mess" runat="server"/></p></form>

</body></html>

Click on the image:

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 290: ASP.Net

ASP.NET Label Control

Web Server Controls

Definition and UsageThe Label control is used to display text on a page. The text is programmable.

Note: This control lets you apply styles to its content!

Properties

Property Description

runat Specifies that the control is a server control. Must be set to "server"

Text The text to display in the label

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleLabelDeclare one Label control, one TextBox control, and one Button control in an .aspx file. When the userclicks on the button, the submit subroutine is executed. The subroutine copies the content of theTextBox control to the Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 291: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(Sender As Object, e As EventArgs) label1.Text=txt1.TextEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server">Write some text:<asp:TextBox id="txt1" Width="200" runat="server" /><asp:Button id="b1" Text="Copy to Label" OnClick="submit"runat="server" /><p><asp:Label id="label1" runat="server" /></p></form>

</body></html>

Write some text:

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 292: ASP.Net

ASP.NET LinkButton Control

Web Server Controls

Definition and UsageThe LinkButton control is used to create a hyperlink button.

Note: This control looks like a HyperLink control but has the same functionality as the Button control.

Properties

Property Description .NET

CausesValidation Specifies if a page is validated when a LinkButton control is clicked 1.0

CommandArgument Additional information about the command to perform 1.0

CommandName The command associated with the Command event 1.0

OnClientClick The name of the function to be executed when the LinkButton is clicked 2.0

PostBackUrl The URL of the page to post to from the current page when the LinkButton control is clicked 2.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

Text The text on the LinkButton 1.0

ValidationGroup The group of controls for which the LinkButton control causes validation when it posts back to theserver

2.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleLinkButtonDeclare one LinkButton control and one Label control in an .aspx file. When the user clicks on the link, the lbClick subroutine is executed. The subroutinesends the text "You clicked the LinkButton control" to the Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 293: ASP.Net

ASP.NET OnClientClick Property

Complete LinkButton Control Reference

Definition and UsageThe OnClientClick property is used to sets a client side script to be run when the LinkButton control is clicked.

The script specified in this property is run by the LinkButton's event "OnClick" in addition to the predefined script.

Syntax

<asp:LinkButton OnClientClick="func" runat="server" />

Attribute Description

func Client side script to be run when LinkButton is clicked

Example

The following example runs two scripts when the LinkButton control is clicked:

<script runat="server">Sub script1(obj As Object, e As EventArgs) lblMsg.Text="Hello!"End Sub</script>

<html><body>

<form runat="server"><asp:LinkButton OnClick="script1" OnClientClick="script2()"Text="Click Me" runat="server" /><br /><asp:label id="lblMsg" runat="server" /></form>

<script type="text/javascript">function script2() { return confirm('Hello!'); }</script></body></html>

Show example »

Complete LinkButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 294: ASP.Net

ASP.NET PostBackUrl Property

Complete LinkButton Control Reference

Definition and UsageThe PostBackUrl property is used to gets or sets the URL of the page to post when the LinkButtoncontrol is clicked.

Syntax

<asp:LinkButton PostBackUrl="string" runat="server" />

Attribute Description

string String specifying the URL of the page to post to. Default is an empty string, thiscauses the page to post back to itself

Example

The following example sets the post URL of a LinkButton control:

<form runat="server"> Name:<asp:TextBox id="TextBox1" runat=Server /> <asp:LinkButton id="Button1" Text="Submit" PostBackUrl="demo_postbackurl.aspx" runat="Server" /></form>

Show example »

Complete LinkButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 295: ASP.Net

ASP.NET Text Property

Complete LinkButton Control Reference

Definition and UsageThe Text property is used to set or return the text on a LinkButton control.

Note: This control looks like a HyperLink control but has the same functionality as the Button control.

Syntax

<asp:LinkButton Text="string" runat="server" />

Attribute Description

string A string that specifies the text on the LinkButton control

Example

The following example sets the text on a LinkButton control:

<form runat="server"><asp:LinkButton id="lbt1" runat="server" Text="Submit" /></form>

Show example »

Complete LinkButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 296: ASP.Net

ASP.NET ValidationGroup Property

Complete LinkButton Control Reference

Definition and UsageThe ValidationGroup property specifies which group of control is validated on validation.

This property is mostly used when there are several buttons in a form.

Syntax

<asp:LinkButton ValidationGroup="group" runat="server" />

Attribute Description

group The group of controls to validate.

Example

The following example validates the specific validation group:

<asp:TextBox id="tb1" runat=Server /><asp:RequiredFieldValidator id="ReqField1" ControlToValidate="tb1"ValidationGroup="valGroup1" ErrorMessage="Required" runat="server" />

<asp:LinkButton id="Button2" Text="Validate" CausesValidation="True"ValidationGroup="valGroup2" runat="server" />

Show example »

Complete LinkButton Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 297: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub lblClick(sender As Object, e As EventArgs) Label1.Text="You clicked the LinkButton control"End Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:LinkButton Text="Click me!" OnClick="lblClick"runat="server" /><p><asp:Label id="Label1" runat="server" /></p></form>

</body></html>

Click me!

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 298: ASP.Net

ASP.NET ListBox Control

Web Server Controls

Definition and UsageThe ListBox control is used to create a single- or multi-selection drop-down list.

Each selectable item in a ListBox control is defined by a ListItem element!

Tip: This control supports data binding!

Properties

Property Description .NET

Rows The number of rows displayed in the list 1.0

SelectionMode Allows single or multiple selections 1.0

ListControl Standard Properties

AppendDataBoundItems, AutoPostBack, CausesValidation, DataTextField,DataTextFormatString, DataValueField, Items, runat, SelectedIndex,SelectedItem, SelectedValue, TagKey, Text, ValidationGroup,OnSelectedIndexChanged

The ListControl control covers all the base functions for list controls. Controls that inherits from this control include the CheckBoxList, DropDownList, ListBox,and RadioButtonList controls.

For a full description, go to ListControl Standard Attributes.

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleListboxDeclare one ListBox control in an .aspx file. Then create an event handler for the Click event which displays some text and the selected item, in a Labelcontrol.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 299: ASP.Net

ASP.NET Rows Property

Complete ListBox Control Reference

Definition and UsageThe Rows property is used to get or set the number of rows visible (without scrolling) in the ListBox.

Syntax

<asp:ListBox Rows="num" runat="server">Some Content</asp:ListBox>

Attribute Description

num Specifies the number of rows visible (without scrolling) in the ListBox.

Example

The following example sets the Rows property of a ListBox control:

<form runat="server"><asp:ListBox id="lb1" Rows="5" runat="server"> <asp:ListItem Value="Item1" /> <asp:ListItem Value="Item2" /> <asp:ListItem Value="Item3" /> <asp:ListItem Value="Item4" /> <asp:ListItem Value="Item5" /></asp:ListBox></form>

Show example »

Complete ListBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 300: ASP.Net

ASP.NET SelectionMode Property

Complete ListBox Control Reference

Definition and UsageThe SelectionMode property is used to get or set how a user is allowed to select ListBox items.

Syntax

<asp:ListBox SelectionMode="mode" runat="server">Some Content</asp:ListBox>

Attribute Description

mode Specifies how a users is allowed to select items.

Possible values:

Single - Default. Multiple items can not be selectedMultiple - Multiple items can be selected

Example

The following example sets the SelectionMode of a ListBox control:

<form runat="server"><asp:Calendar id="cal1" runat="server"SelectionMode="Multiple" /></form>

Show example »

Complete ListBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 301: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(Sender As Object,e As EventArgs)mess.Text="You selected " & drop1.SelectedItem.TextEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:ListBox id="drop1" rows="3" runat="server"><asp:ListItem selected="true">Item 1</asp:ListItem><asp:ListItem>Item 2</asp:ListItem><asp:ListItem>Item 3</asp:ListItem><asp:ListItem>Item 4</asp:ListItem><asp:ListItem>Item 5</asp:ListItem><asp:ListItem>Item 6</asp:ListItem></asp:ListBox><asp:Button Text="Submit" OnClick="submit" runat="server" /><p><asp:label id="mess" runat="server" /></p></form>

</body></html>

Item 1Item 2Item 3Item 4Item 5

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 302: ASP.Net

ASP.NET ListItem Control

Web Server Controls

Definition and UsageThe ListItem control creates an item in a list.

This control is used with the list controls such as <asp:ListBox>, <asp:RadioButtonList> and<asp:BulletedList>.

Syntax

<asp:ListItemEnabled="True|False"Selected="True|False"Text="label"Value="value" />

Properties

Property Description .NET

Attributes Optional. A collection of attribute name and value pairs for theListItem that are not directly supported by the class

1.0

Enabled Optional. Specifies if the item is enabled or disabled 2.0

Selected Optional. Specifies whether or not the item is selected 1.0

Text Optional. The text displayed in the ListItem 1.0

Value Optional. The value of the the ListItem. 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

It is possible to use the Text or Value properties and the inner HTML text to set the text displayed foran item in the list.

Example

<asp:ListItem Value="Text1" Text="Text2">Text3</asp:ListItem>

Depending on the combination of the three, different texts are shown and values used. The table belowshows all possible combinations and their results:

Inner HTML Text Property Value Property Text Shown Value Used

Set Set Set Inner HTML Value Property

Set Set Not set Inner HTML Inner HTML

Set Not set Set Inner HTML Value Property

Set Not set Not set Inner HTML Inner HTML

Not set Set Set Text Property Value Property

Not set Set Not set Text Property Text Property

Not set Not set Set Value Property Value Property

Not set Not set Not set Not set Not set

Tips and NotesNote: The Text and Value properties have a default value of an empty string. Because of this it ispossible to have empty list items.

Examples

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 303: ASP.Net

Basic ListItem in BulletedListA BulletedList control with two ListItems in an .aspx file.

ListItems with different properties in ListBoxA ListBox control with some ListItems in an .aspx file. The items in the list uses different properties toshow the ListItem text.

ListItem disabled in ListBoxA ListBox control with one of the ListItems disabled.

ListItem selected in RadioButtonListA RadioButtonList control with one of the ListItems selected.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 304: ASP.Net

ASP.NET Enabled Property

Complete ListItem Control Reference

Definition and UsageThe Enabled property is used to set or return the whether or not the ListItem is enabled by default.

If this property is set to TRUE the ListItem is Enabled by default, otherwise FALSE. Default is TRUE.

Syntax

<asp:ListItem Enabled="True|False" runat="server" />

Example

The following example disables a ListItem in a ListBox control:

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Text="Item1" Enabled="False"/><asp:ListItem Text="Item2" /></asp:ListBox></form>

Show example »

Complete ListItem Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 305: ASP.Net

ASP.NET Selected Property

Complete ListItem Control Reference

Definition and UsageThe Selected property is used to set or return the whether or not the ListItem is selected by default.

If this property is set to TRUE the ListItem is selected by default, otherwise FALSE. Default is FALSE.

Syntax

<asp:ListItem Selected="True|False" runat="server" />

Example

The following example sets the Selected ListItem in a ListBox control:

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Text="Item1" Selected="True"/><asp:ListItem Text="Item2" /></asp:ListBox></form>

Show example »

Complete ListItem Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 306: ASP.Net

ASP.NET Text Property

Complete ListItem Control Reference

Definition and UsageThe Text property is used to set or return the text of a ListItem control.

Syntax

<asp:ListItem Text="string" runat="server" />

Attribute Description

string A string that specifies the text of the ListItem control

It is possible to use the Text or Value properties and the inner HTML text to set the text displayed foran item in the list.

Example

<asp:ListItem Value="Text1" Text="Text2">Text3</asp:ListItem>

Depending on the combination of the three, different texts are shown and values used. The table belowshows all possible combinations and their results:

Inner HTML Text Property Value Property Text Shown Value Used

Set Set Set Inner HTML Value Property

Set Set Not set Inner HTML Inner HTML

Set Not set Set Inner HTML Value Property

Set Not set Not set Inner HTML Inner HTML

Not set Set Set Text Property Value Property

Not set Set Not set Text Property Text Property

Not set Not set Set Value Property Value Property

Not set Not set Not set Not set Not set

Tips and NotesNote: The Text and Value properties have a default value of an empty string. Because of this it ispossible to have empty list items.

Example

The following example sets the text of a ListItem in a ListBox control:

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Text="Item1" /><asp:ListItem Text="Item2" /></asp:ListBox></form>

Show example »

Complete ListItem Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 307: ASP.Net

ASP.NET Value Property

Complete ListItem Control Reference

Definition and UsageThe Value property is used to set or return the value of a ListItem control.

Syntax

<asp:ListItem Value="string" runat="server" />

Attribute Description

string A string that specifies the value of the ListItem control

It is possible to use the Text or Value properties and the inner HTML text to set the text displayed foran item in the list.

Example

<asp:ListItem Value="Text1" Text="Text2">Text3</asp:ListItem>

Depending on the combination of the three, different texts are shown and values used. The table belowshows all possible combinations and their results:

Inner HTML Text Property Value Property Text Shown Value Used

Set Set Set Inner HTML Value Property

Set Set Not set Inner HTML Inner HTML

Set Not set Set Inner HTML Value Property

Set Not set Not set Inner HTML Inner HTML

Not set Set Set Text Property Value Property

Not set Set Not set Text Property Text Property

Not set Not set Set Value Property Value Property

Not set Not set Not set Not set Not set

Tips and NotesNote: The Text and Value properties have a default value of an empty string. Because of this it ispossible to have empty list items.

Example

The following example sets the Value of a ListItem in a ListBox control:

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Value="Item1" /><asp:ListItem Value="Item2" /></asp:ListBox></form>

Show example »

Complete ListItem Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 308: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:BulletedList runat="server"><asp:ListItem Text="Item1" /><asp:ListItem Text="Item2" /></asp:BulletedList></form>

</body></html>

Item1Item2

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 309: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Text="Text1" /><asp:ListItem Value="Text3" Text="Text1">Text2</asp:ListItem><asp:ListItem Value="Text3" /></asp:ListBox></form>

</body></html>

Text1Text2Text3

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 310: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:ListBox runat="server"><asp:ListItem Text="Item1" /><asp:ListItem Text="Item2" /><asp:ListItem Text="Item3" /><asp:ListItem Text="Item4" enabled="False"/></asp:ListBox></form>

</body></html>

Item1Item2Item3

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 311: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:RadioButtonList runat="server"><asp:ListItem Text="Item1" /><asp:ListItem Text="Item2" /><asp:ListItem Text="Item3" /><asp:ListItem Text="Item4" selected="True"/></asp:RadioButtonList></form>

</body></html>

Item1Item2Item3Item4

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 312: ASP.Net

ASP.NET Literal Control

Web Server Controls

Definition and UsageThe Literal control is used to display text on a page. The text is programmable.

Note: This control does not let you apply styles to its content!

Properties

Property Description .NET

Mode 2.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

Text Specifies the text to display 1.0

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExamplesLiteralDeclare one Literal control which displays some static text in an .aspx file.

Literal 2Declare one Literal control and one Button control in an .aspx file. When the user clicks on the button,the submit subroutine is executed. The subroutine changes the text of the Literal control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 313: ASP.Net

ASP.NET Text Property

Complete Literal Control Reference

Definition and UsageThe Text property is used to set or return the text of a Literal control.

If the text is set in the ASP.NET code the (like in the example below) text is HTML decoded before it isdisplayed. However, if the property is set programmatically or set as text between the opening andclosing tags of the control, the caption is not HTML decoded.

Syntax

<asp:HyperLink Text="string" runat="server" />

Attribute Description

string A string that specifies the text in the literal control

Example

The following example sets the text for the Literal control:

<form runat="server"><asp:Literal runat="server" Text="W3Schools" /></form>

Show example »

Complete Literal Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 314: ASP.Net

ASP.NET Panel Control

Web Server Controls

Definition and UsageThe Panel control is used as a container for other controls.

Tip: This control is often used to generate controls by code and to display and hide groups of controls.

Note: This control renders as an HTML <div> element.

Properties

Property Description .NET

BackImageUrl Specifies a URL to an image file to display as a background forthis control

1.0

DefaultButton Specifies the ID of the default button in the Panel 2.0

Direction Specifies the content display direction of the Panel 2.0

GroupingText Specifies the caption for the group of controls in the Panel 2.0

HorizontalAlign Specifies the horizontal alignment of the content 1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

ScrollBars Specifies the position and visibility of scroll bars in the Panel 2.0

Wrap Specifies whether the content should wrap or not 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExamplePanelDeclare one Panel control, one CheckBox control, and one Button control in an .aspx file. When theuser checks the CheckBox control, and the clicks the Refresh button, the Panel control will hide.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 315: ASP.Net

ASP.NET BackImageUrl Property

Complete Panel Control Reference

Definition and UsageThe BackImageUrl property is used to set or return the URL of an image to use as background imagefor the Panel Control.

Syntax

<asp:Panel BackImageUrl="URL" runat="server">Some Content</asp:Panel>

Attribute Description

URL The URL of the image to use

Example

The following example sets the BackImageUrl for a Panel control:

<form runat="server"><asp:Panel id="Pan1" runat="server" BackImageUrl="img.gif">Hello!</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 316: ASP.Net

ASP.NET DefaultButton Property

Complete Panel Control Reference

Definition and UsageThe DefaultButton property is used to set or return the id of the default button for the Panel Control.

This property is used to specify which button gets clicked when the Panel control has focus and the"ENTER" key is pressed.

Syntax

<asp:Panel DefaultButton="button_id" runat="server">Some Content</asp:Panel>

Attribute Description

button_id The id of the button to use as default button

Example

The following example sets the DefaultButton for a Panel control:

<form runat="server"><asp:Panel runat="server" DefaultButton="bt1">

<asp:TextBox runat="server" /><asp:Button id="bt1" Text="Default" runat="server" />

</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 317: ASP.Net

ASP.NET Direction Property

Complete Panel Control Reference

Definition and UsageThe Direction property is used to set or return the ontent display direction of the Panel.

This property is used specify the display direction for controls that include text in the Panel.

Syntax

<asp:Panel Direction="direction" runat="server">Some Content</asp:Panel>

Attribute Description

direction Specifies the content display direction of the panel

Possible values:

NotSet - Default. The content direction is not setLeftToRight - The content direction is left to rightRightToLeft - The content direction is right to left

Example

The following example changes the Direction property for a Panel control:

<form runat="server"><asp:Panel id="pan1" runat="server" Direction="RightToLeft">Hello!</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 318: ASP.Net

ASP.NET GroupingText Property

Complete Panel Control Reference

Definition and UsageThe GroupingText property is used to set or return caption text for the group of controls in the Panel Control.

This property is used to display a frame and caption for the Panel control.

Syntax

<asp:Panel GroupingText="string" runat="server">Some Content</asp:Panel>

Attribute Description

string The string to display as caption text for the Panel

Example

The following example sets the GroupingText for a Panel control:

<form runat="server"><asp:Panel id="pan1" runat="server" GroupingText="Panel" >Hello!</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 319: ASP.Net

ASP.NET HorizontalAlign Property

Complete Panel Control Reference

Definition and UsageThe HorizontalAlign property is used to set or return horizontal alignment of the content in the Panel Control.

Syntax

<asp:Panel HorizontalAlign="align" runat="server">Some Content</asp:Panel>

Attribute Description

align Specifies the horizontal alignment of the content.

Possible values:

CenterJustifyLeftNotSet (Default)Right

Example

The following example sets the HorizontalAlign property of a Panel control:

<form runat="server"><asp:Panel id="pan1" runat="server" HorizontalAlign="Right" >Hello!</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 320: ASP.Net

ASP.NET ScrollBars Property

Complete Panel Control Reference

Definition and UsageThe ScrollBars property is used to set or return the position and visibility of scroll bars in the Panelcontrol

Syntax

<asp:Panel ScrollBars="value" runat="server">Some Content</asp:Panel>

Attribute Description

value Specifies the which scrollbars are shown or not shown.

Possible values:

None - Default. No scroll bars are shownHorizontal - Only a horizontal scroll bar is shownVertical - Only a vertical scroll bar is shownBoth - Horizontal and vertical scroll bars are shownAuto - Horizontal, vertical, or both scroll bars are shown if needed

Example

The following example sets the ScrollBars property to "Auto" in a Panel control:

<form runat="server"><asp:Panel id="pan1" runat="server"Height="100px" ScrollBars="Auto">

Some content

</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 321: ASP.Net

ASP.NET Wrap Property

Complete Panel Control Reference

Definition and UsageThe Wrap property is used to set or return whether or not content should wrap in the Panel control.

Syntax

<asp:Panel Wrap="TRUE|FALSE" runat="server">Some Content</asp:Panel>

Example

The following example sets the Wrap property to "FALSE" in a Panel control:

<form runat="server"><asp:Panel ID="Pan1" Width="250px"Wrap="FALSE" runat="server">

Some content

</asp:Panel></form>

Show example »

Complete Panel Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 322: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub Page_Load(sender As Object, e As EventArgs) if check1.Checked then panel1.Visible=false else panel1.Visible=true end ifEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:Panel id="panel1"runat="server" BackColor="#ff0000"Height="100px" Width="100px">Hello World!</asp:Panel><asp:CheckBox id="check1"Text="Hide Panel control"runat="server"/><br /><br /><asp:Button Text="Reload" runat="server" /></form>

</body></html>

Hello World!

Hide Panel control

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 323: ASP.Net

ASP.NET PlaceHolder Control

Web Server Controls

Definition and UsageThe PlaceHolder control is used to reserve space for controls added by code.

Note: The PlaceHolder control does not produce any visible output (it only acts as a container for othercontrols on the Web page).

Properties

Property Description

runat Specifies that the control is a server control. Must be set to "server"

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 324: ASP.Net

ASP.NET RadioButton Control

Web Server Controls

Definition and UsageThe RadioButton control is used to display a radio button.

Tip: To create a set of radio buttons using data binding, use the RadioButtonList control!

Properties

Property Description

AutoPostBack A Boolean value that specifies whether the form should be posted immediately after the Checked property haschanged or not. Default is false

Checked A Boolean value that specifies whether the radio button is checked or not

id A unique id for the control

GroupName The name of the group to which this radio button belongs

OnCheckedChanged The name of the function to be executed when the Checked property has changed

runat Specifies that the control is a server control. Must be set to "server"

Text The text next to the radio button

TextAlign On which side of the radio button the text should appear (right or left)

ExampleRadiobuttonDeclare three RadioButton controls, one Button control, and one Label control in an .aspx file. When the submit button is triggered, the submit subroutine isexecuted. The submit subroutine may respond in three ways: if the radiobutton with id="red" is selected, the server sends the message "You selected Red"to the Label control. If the radiobutton with id="green" is selected, the server sends the message "You selected Green" to the Label control. If theradiobutton with id="green" is selected, the server sends the message "You selected Blue" to the Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 325: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(Sender As Object, e As EventArgs)if red.Checked then Label1.Text="You selected " & red.TextelseIf green.Checked then Label1.Text="You selected " & green.TextelseIf blue.Checked then Label1.Text="You selected " & blue.Textend ifEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server">Select your favorite color:<br /><asp:RadioButton id="red" Text="Red" Checked="True" GroupName="colors" runat="server"/><br /><asp:RadioButton id="green" Text="Green"GroupName="colors" runat="server"/><br /><asp:RadioButton id="blue" Text="Blue" GroupName="colors" runat="server"/><br /><asp:Button text="Submit" OnClick="submit" runat="server"/><p><asp:Label id="Label1" runat="server"/></p></form>

</body></html>

Select your favorite color: Red Green Blue

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 326: ASP.Net

ASP.NET RadioButtonList Control

Web Server Controls

Definition and UsageThe RadioButtonList control is used to create a group of radio buttons.

Each selectable item in a RadioButtonList control is defined by a ListItem element!

Tip: This control supports data binding!

Properties

Property Description .NET

CellPadding The amount of pixels between the border and the contents of thetable cell

1.0

CellSpacing The amount of pixels between table cells 1.0

RepeatColumns The number of columns to use when displaying the radio buttongroup

1.0

RepeatDirection Specifies whether the radio button group should be repeatedhorizontally or vertically

1.0

RepeatLayout The layout of the radio button group 1.0

runat Specifies that the control is a server control. Must be set to "server" 1.0

TextAlign On which side of the radio button the text should appear 1.0

ListControl Standard Properties

AppendDataBoundItems, AutoPostBack, CausesValidation, DataTextField,DataTextFormatString, DataValueField, Items, runat, SelectedIndex,SelectedItem, SelectedValue, TagKey, Text, ValidationGroup,OnSelectedIndexChanged

The ListControl control covers all the base functions for list controls. Controls that inherits from thiscontrol include the CheckBoxList, DropDownList, ListBox, and RadioButtonList controls.

For a full description, go to ListControl Standard Attributes.

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleRadiobuttonListDeclare one RadioButtonList control, one Button control, and one Label control in an .aspx file. Then wecreate an event handler for the Click event which displays some text and the selected item, in a Labelcontrol.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 327: ASP.Net

ASP.NET CellPadding Property

Complete RadioButtonList Control Reference

Definition and UsageThe CellPadding property is used to get or set the amount of pixels between the border and thecontents of the table cell.

Note: This function only works if the RepeatLayout property is set to "Table"

Syntax

<asp:RadioButtonList CellPadding="pixels" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

pixels Specifies the amount of pixels between the border and the contents of the tablecell.

Example

The following example sets the CellPadding property of a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" CellPadding="15">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 328: ASP.Net

ASP.NET CellSpacing Property

Complete RadioButtonList Control Reference

Definition and UsageThe CellSpacing property is used to get or set the amount of pixels between table cells in theRadioButtonList.

Note: This function only works if the RepeatLayout property is set to "Table" (default).

Syntax

<asp:RadioButtonList CellSpacing="pixels" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

pixels Specifies the amount of pixels between the table cells.

Example

The following example sets the CellSpacing property of a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" CellSpacing="15">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 329: ASP.Net

ASP.NET RepeatColumns Property

Complete RadioButtonList Control Reference

Definition and UsageThe RepeatColumns property is used to get or set the number of columns to use when displaying the radio button list.

Syntax

<asp:RadioButtonList RepeatColumns="num" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

num Specifies the number of columns to display. Default is "1"

Example

The following example sets the RepeatColumns property to "2" in a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" RepeatColumns="2">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 330: ASP.Net

ASP.NET RepeatDirection Property

Complete RadioButtonList Control Reference

Definition and UsageThe RepeatDirection property is used to get or set if the items in the RadioButtonList are displayed vertically or horizontally.

Syntax

<asp:RadioButtonList RepeatDirection="mode" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

mode Specifies the layout direction of the items in the RadioButtonList.

Possible values:

Horizontal - Items are displayed horizontallyVertical - Default. Items are displayed vertically

Example

The following example sets the RepeatDirection of a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" RepeatDirection="Horizontal">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 331: ASP.Net

ASP.NET RepeatLayout Property

Complete RadioButtonList Control Reference

Definition and UsageThe RepeatLayout property is used to get or set how items are displayed in the RadioButtonList.

Syntax

<asp:RadioButtonList RepeatLayout="mode" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

mode Specifies the layout of the items in the RadioButtonList.

Possible values:

Flow - Items are not displayed in a tableTable - Default. Items are displayed in a table

Example

The following example sets the RepeatLayout of a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" RepeatLayout="Flow">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 332: ASP.Net

ASP.NET TextAlign Property

Complete RadioButtonList Control Reference

Definition and UsageThe TextAlign property is used to get or set the text alignment for the text of the RadioButtonListitems.

Syntax

<asp:RadioButtonList TextAlign="align" runat="server">Some Content</asp:RadioButtonList >

Attribute Description

align Specifies the alignment of the text for the list item

Possible values:

LeftRight (default)

Example

The following example sets the TextAlign property to "Left" in a RadioButtonList control:

<form runat="server"><asp:RadioButtonList id="rb1"runat="server" TextAlign="Left">

Some content

</asp:RadioButtonList></form>

Show example »

Complete RadioButtonList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 333: ASP.Net

ASP.NET BulletedList Control

Web Server Controls

Definition and UsageThe BulletedList control creates a list in bullet format.

Each item in a BulletedList control is defined by a ListItem element!

Note: This class is new in ASP.NET 2.0.

Properties

Property Description .NET

BulletImageUrl Specifies the URL of a custom bullet list image. Used if "BulletStyle"is "CustomImage"

2.0

BulletStyle Specifies the style of the bullet list 2.0

DisplayMode Specifies the type of list displayed 2.0

FirstBulletNumber Specify the start number of list items in an ordered list 2.0

runat Required. Specifies that the control is a server control. Must be setto "server"

1.0

Target Specifies where to open the target URL 2.0

ListControl Standard Properties

AppendDataBoundItems, CausesValidation, DataTextField, DataTextFormatString,DataValueField, Items, ValidationGroup

The ListControl control covers all the base functions for list controls. The properties above applies tothe BulletedList control.

For a full description, go to ListControl Standard Attributes.

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 334: ASP.Net

ASP.NET BulletImageUrl Property

Complete BulletedList Control Reference

Definition and UsageThe BulletImageUrl property is used to get or set the URL of the image used when the BulletStyleproperty is set to "CustomImage".

Syntax

<asp:BulletedList BulletImageUrl="url" runat="server">Some Content</asp:BulletedList>

Attribute Description

url String specifying the URL of image to use as bullet marker

Example

The following example sets the BulletImageUrl of a BulletedList control:

<form runat="server"><asp:BulletedList id="bl1" runat="server"BulletImageUrl="image.gif">

Some content

</asp:BulletedList></form>

Show example »

Complete BulletedList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 335: ASP.Net

ASP.NET BulletStyle Property

Complete BulletedList Control Reference

Definition and UsageThe BulletStyle property is used to get or set the style of the bullet list marker.

Syntax

<asp:BulletedList BulletStyle="style" runat="server">Some Content</asp:BulletedList>

Attribute Description

style Specifies the style of the list item marker.

Possible values:

NotSet - Not setCircle - Empty circleDisc - Filled circleSquare - Filled squareNumbered - NumberLowerAlpha - Lowercase letterUpperAlpha - Uppercase letterLowerRoman - Lowercase Roman numeralUpperRoman - Uppercase Roman numeralCustomImage - Custom image (defined by the "BulletImageUrl" property)

Example

The following example sets the BulletStyle of a BulletedList control:

<form runat="server"><asp:BulletedList id="bl1"runat="server" BulletStyle="Numbered">

Some content

</asp:BulletedList></form>

Show example »

Complete BulletedList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 336: ASP.Net

ASP.NET DisplayMode Property

Complete BulletedList Control Reference

Definition and UsageThe DisplayMode property is used to get or set the type of list displayed.

Syntax

<asp:BulletedList DisplayMode="mode" runat="server">Some Content</asp:BulletedList>

Attribute Description

mode Specifies the list item display mode.

Possible Values:

Text - Default. Standard TextHyperLink - HyperlinkLinkButton - Hyperlink Button

Example

The following example sets the DisplayMode of a BulletedList control:

<form runat="server"><asp:Bulletedlist DisplayMode="HyperLink"id="bl1" runat="server"> <asp:ListItem Text="W3Schools" Value="http://www.w3schools.com/" /></asp:Bulletedlist></form>

Show example »

Complete BulletedList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 337: ASP.Net

ASP.NET FirstBulletNumber Property

Complete BulletedList Control Reference

Definition and UsageThe FirstBulletNumber property is used to get or set the number of the first item in an orderedBulletedList control.

Syntax

<asp:BulletedList FirstBulletNumber="num" runat="server">Some Content</asp:BulletedList>

Attribute Description

num Specifies the number of the first list item in an ordered list.

Example

The following example sets the FirstBulletNumber of a BulletedList control:

<form runat="server"><asp:BulletedList id="bl1" runat="server"FirstBulletNumber="4">

Some content

</asp:BulletedList></form>

Show example »

Complete BulletedList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 338: ASP.Net

ASP.NET Target Property

Complete BulletedList Control Reference

Definition and UsageThe Target property is used to get or set where to open the target URL.

Syntax

<asp:BulletedList Target="target" runat="server">Some Content</asp:BulletedList>

Attribute Description

target Specifies where to open the target URL.

Possible Values:

_blank - the target URL will open in a new window_self - the target URL will open in the same frame as it was clicked_search - the target URL will open in the search pane_top - the target URL will open in the full body of the window_parent - the target URL will open in the parent framesetframename - specify a target frame name

Tips and NotesNote: This property is only used when DisplayMode property is "HyperLink"

Example

The following example sets the Target of a BulletedList control:

<form runat="server"><asp:Bulletedlist Target="HyperLink"id="bl1" runat="server"> <asp:ListItem Text="W3Schools" Target="_blank" Value="http://www.w3schools.com/" /></asp:Bulletedlist></form>

Show example »

Complete BulletedList Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 339: ASP.Net

ASP.NET Style Control

Web Server Controls

Definition and UsageThe Style control is used to set the style of a web control.

Properties

Property Description .NET

BackColor The background color of the control 1.0

BorderColor The border color of the control 1.0

BorderStyle The border style of the control 1.0

BorderWidth The border width of the control 1.0

CssClass The CSS class rendered by the control on the client 1.0

Font The font properties of the control 1.0

ForeColor The foreground color (typically the color of the text) of the control 1.0

Height The height of the control 1.0

RegisteredCssClass The CSS class that is registered with the control 2.0

Width The width of the control 1.0

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 340: ASP.Net

ASP.NET BackColor Property

Complete Style Control Reference

Definition and UsageThe BackColor property is used to set or return the background color of a control.

Syntax

<asp:webcontrol id="id" BackColor="color" runat="server" />

Attribute Description

color The color to set as background color of a control. Must be a valid HTML color

Example

The following example sets the background color of a button:

<form runat="server"><asp:Button id="button1" Text="Submit"BackColor="#FFCC80" runat="server" /></form>

Show example »

Try-It-Yourself DemosSet the background color of a Button control (with declaration and script)

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 341: ASP.Net

ASP.NET BorderColor Property

Complete Style Control Reference

Definition and UsageThe BorderColor property is used to set or return the border color of a control.

Syntax

<asp:webcontrol id="id" BorderColor="color" runat="server" />

Attribute Description

color The color to set as background color of a control. Must be a valid HTML color

Example

The following example sets the border color of a table:

<form runat="server"><asp:Table runat="server" BorderColor="#FF0000"BorderWidth="5" GridLines="vertical"> <asp:TableRow> <asp:TableCell>Hello</asp:TableCell> <asp:TableCell>World</asp:TableCell> </asp:TableRow></asp:Table></form>

Show example »

Try-It-Yourself DemosSet the border color of a Button control (with declaration and script)

Complete Style Control Referenc

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 342: ASP.Net

ASP.NET BorderStyle Property

Complete Style Control Reference

Definition and UsageThe BorderStyke property is used to set or return the border style of a control.

Syntax

<asp:webcontrol id="id" BorderStyle="style" runat="server" />

Possible Style Values

Value Description

NotSet Border style is not set

None Defines no border

Dotted Defines a dotted border

Dashed Defines a dashed border

Solid Defines a solid border

Double Defines two borders. The width of the two borders are the same as the border-width value

Groove Defines a 3D grooved border. The effect depends on the border-color value

Ridge Defines a 3D ridged border. The effect depends on the border-color value

Inset Defines a 3D inset border. The effect depends on the border-color value

Outset Defines a 3D outset border. The effect depends on the border-color value

Example

The following example sets the border style of a table:

<form runat="server"><asp:Table runat="server" BorderStyle="dotted"BorderWidth="5" GridLines="vertical"> <asp:TableRow> <asp:TableCell>Hello</asp:TableCell> <asp:TableCell>World</asp:TableCell> </asp:TableRow></asp:Table></form>

Show example »

Try-It-Yourself DemosSet the border color of a Button control (with declaration and script)

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 343: ASP.Net

ASP.NET BorderWidth Property

Complete Style Control Reference

Definition and UsageThe BorderWidth property is used to set or return the border width of a control.

Syntax

<asp:webcontrol id="id" BorderWidth="length" runat="server" />

Attribute Description

length The width of the border. Must be a valid .NET length unit. Valid length units are:cm, mm, in, pt, pc, or px

Example

The following example sets the border width of a table:

<form runat="server"> <asp:Table runat="server" BorderWidth="5"GridLines="vertical"> <asp:TableRow> <asp:TableCell>Hello</asp:TableCell> <asp:TableCell>World</asp:TableCell> </asp:TableRow> </asp:Table></form>

Show example »

Try-It-Yourself DemosSet the border width of a Button control (with declaration and script)

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 344: ASP.Net

ASP.NET CssClass Property

Complete Style Control Reference

Definition and UsageThe CssClass property is used to set or return a CSS style class to a control.

Syntax

<asp:webcontrol id="id" CssClass="style" runat="server" />

Attribute Description

style A String specifying the CSS class used on the control

Example

The following example sets the CSS style to a button:

<style>.TestStyle { font: 12pt verdana; font-weight:700; color:orange; }</style>

<form runat="server"><asp:Button id="Button" CssClass="TestStyle"Text="Submit" runat="server"/></form>

Show example »

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 345: ASP.Net

ASP.NET Font Property

Complete Style Control Reference

Definition and UsageThe Font property is used to set or return the font of a control.

Syntax

<asp:webcontrol id="id" font-subproperty="value" runat="server" />

Font SubProperties

Value Description

Bold Bold sub property. Possible values are TRUE or FALSE

Italic Italic sub property. Possible values are TRUE or FALSE

Name Font name property (like "Verdana" or "Arial"). When you set this property, the Names property is automatically updated with a single elementarray with the value of the Name property

Names An array of font names. When you set this property, the Name property is automatically updated with the first element in the array

Strikeout Strikeout sub property. Possible values are TRUE or FALSE

Underline Strikeout sub property. Possible values are TRUE or FALSE

Size Font size sub property. Specify the font size

Example

The following example sets the font of a button control:

<form runat="server"><asp:Button id="Button1" Text="Submit"Font-Name="Verdana" Font-Size="15" runat="server"/></form>

Show example »

Try-It-Yourself DemosSet the Font of a Button control (with declaration and script)

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 346: ASP.Net

ASP.NET ForeColor Property

Complete Style Control Reference

Definition and UsageThe ForeColor property is used to set or return the foreground color (normally the text color) of acontrol.

Syntax

<asp:webcontrol id="id" ForeColor="color" runat="server" />

Attribute Description

color The color to set as foreground color of a control. Must be a valid HTML color

Example

The following example sets the foreground color of a button:

<form runat="server"><asp:Button id="button1" Text="Submit"ForeColor="#FF0000" runat="server" /></form>

Show example »

Try-It-Yourself DemosSet the text color of a Button control (with declaration and script)

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 347: ASP.Net

ASP.NET Height Property

Complete Style Control Reference

Definition and UsageThe Height property is used to set or return the height of a control.

Syntax

<asp:webcontrol id="id" Height="value" runat="server" />

Attribute Description

value The height of control. Must be a number representing pixels or a percent value representing the parent objects height

Example

The following example sets the height of a button control:

<form runat="server"><asp:Button id="button1" Text="Submit"Height="50px" runat="server" /></form>

Show example »

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 348: ASP.Net

ASP.NET Width Property

Complete Style Control Reference

Definition and UsageThe Width property is used to set or return the width of a control.

Syntax

<asp:webcontrol id="id" Width="value" runat="server" />

Attribute Description

value The width of control. Must be a number representing pixels or a percent valuerepresenting the parent objects width

Example

The following example sets the width of a button control:

<form runat="server"><asp:Button id="button1" Text="Submit"Width="150px" runat="server" /></form>

Show example »

Complete Style Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 349: ASP.Net

ASP.NET Table Control

Web Server Controls

Definition and UsageThe Table control is used in conjunction with the TableCell control and the TableRow control to create atable.

Properties

Property Description .NET

BackImageUrl A URL to an image to use as an background for the table 1.0

Caption The caption of the table 2.0

CaptionAlign The alignment of the caption text 2.0

CellPadding The space between the cell walls and contents 1.0

CellSpacing The space between cells 1.0

GridLines The gridline format in the table 1.0

HorizontalAlign The horizontal alignment of the table in the page 1.0

Rows A collection of rows in the Table 1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExamplesTableDeclare two Table controls in an .aspx file.

Table 2Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 350: ASP.Net

ASP.NET BackImageUrl Property

Complete Table Control Reference

Definition and UsageThe BackImageUrl property is used to set or return the URL of an image to use as background imagefor the Table Control.

Syntax

<asp:Table BackImageUrl="URL" runat="server">Some Content</asp:Table>

Attribute Description

URL The URL of the image to use

Example

The following example sets the BackImageUrl for a Table control:

<form runat="server"><asp:Table id="tab1" runat="server" BackImageUrl="img.gif"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 351: ASP.Net

ASP.NET Caption Property

Complete Table Control Reference

Definition and UsageThe Caption property is used to get or set a text that is shown as a caption for the Table Control.

Syntax

<asp:Table Caption="string" runat="server">Some Content</asp:Table>

Attribute Description

string The text to be shown as the table caption

Example

The following example sets the Caption for a Table control:

<form runat="server"><asp:Table id="tab1" runat="server"Caption="Table Example"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 352: ASP.Net

ASP.NET CaptionAlign Property

Complete Table Control Reference

Definition and UsageThe CaptionAlign property is used to get or set the alignment of the caption text for a table.

Syntax

<asp:Table Caption="text" CaptionAlign="align" runat="server">Some Content</asp:Table>

Attribute Description

align Specifies the alignment of the caption text

Possible Values:

NotSet - Default. Caption alignment is not set.Top - Caption is displayed at the top of the table. Text is centeredBottom - Caption is displayed at the bottom of the table. Text is centeredLeft - Caption is displayed at the top of the table. Text is left-alignedRight - Caption is displayed at the top of the table. Text is right-aligned

Example

The following example sets the Caption property in a table and aligns it to the bottom of the Tablecontrol:

<form runat="server"><asp:Table id="tab1" runat="server"Caption="Table Example" CaptionAlign="bottom"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 353: ASP.Net

ASP.NET CellPadding Property

Complete Table Control Reference

Definition and UsageThe CellPadding property is used to get or set the amount of space (in pixels) between the cell border and the cell content.

Syntax

<asp:Table CellPadding="px" runat="server">Some Content</asp:Table>

Attribute Description

px Specifies how many pixels of space there is between the cell border and cell content

Example

The following example sets the CellPadding property of the Table control:

<form runat="server"><asp:Table id="tab1" runat="server"CellPadding="30"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 354: ASP.Net

ASP.NET CellSpacing Property

Complete Table Control Reference

Definition and UsageThe CellSpacing property is used to get or set the amount of space (in pixels) between the cells in atable.

Note: This property does not work in FireFox.

Syntax

<asp:Table CellSpacing="px" runat="server">Some Content</asp:Table>

Attribute Description

px Specifies how many pixels of space there is between the cells

Example

The following example sets the CellSpacing property of the Table control:

<form runat="server"><asp:Table id="tab1" runat="server"CellSpacing="20"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 355: ASP.Net

ASP.NET GridLines Property

Complete Table Control Reference

Definition and UsageThe GridLines property is used to get or set the grid line style of the Table control.

Syntax

<asp:Table GridLines="mode" runat="server">Some Content</asp:Table>

Attribute Description

mode Specifies the grid line style for the table

Possible Values:

NoneHorizontalVerticalBoth

Example

The following example sets the GridLines property to "Both":

<form runat="server"><asp:Table id="tab1" runat="server" GridLines="Both"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 356: ASP.Net

ASP.NET HorizontalAlign Property

Complete Table Control Reference

Definition and UsageThe HorizontalAlign property is used to set or return horizontal alignment of the content in the Table control.

Syntax

<asp:Table HorizontalAlign="align" runat="server">Some Content</asp:Table>

Attribute Description

align Specifies the horizontal alignment of the content.

Possible values:

CenterJustifyLeftNotSet (Default)Right

Example

The following example sets the HorizontalAlign property of a Table control:

<form runat="server"><asp:Table id="tab1" runat="server" HorizontalAlign="Right"><asp:TableRow><asp:TableCell>Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete Table Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 357: ASP.Net

ASP.NET TableCell Control

Web Server Controls

Definition and UsageThe TableCell control is used in conjunction with the Table control and the TableRow control to create acell in a table.

Tip: The cells of each row are stored in the Cells collection of the TableRow control.

Properties

Property Description .NET

AssociatedHeaderCellID A list of table header cells associated with the TableCell control 2.0

ColumnSpan The number of columns this cell should span 1.0

HorizontalAlign The horizontal alignment of the contents in the table cell 1.0

RowSpan The number of rows this cell should span 1.0

runat Specifies that the control is a server control. Must be set to"server"

1.0

Text Specifies the text of the table cell 1.0

VerticalAlign The vertical alignment of the contents in the table cell 1.0

Wrap Specifies whether the cell's contents should wrap or not 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleTableDeclare two Table controls in an .aspx file.

Table 2Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 358: ASP.Net

ASP.NET ColumnSpan Property

Complete TableCell Control Reference

Definition and UsageThe ColumnSpan property is used to set or return number of columns the TableCell spans in a Tablecontrol.

Syntax

<asp:TableCell ColumnSpan="num" runat="server">Some content</asp:TableCell>

Attribute Description

num Specifies the number of columns the TableCell spans

Example

The following example sets the ColumnSpan mode to "2":

<form runat="server"><asp:Table id="tab1" runat="server">

<asp:TableRow><asp:TableCell ColumnSpan="2">Some Content</asp:TableCell></asp:TableRow>

<asp:TableRow><asp:TableCell>Some Content</asp:TableCell><asp:TableCell>Some Content</asp:TableCell></asp:TableRow>

</asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 359: ASP.Net

ASP.NET HorizontalAlign Property

Complete TableCell Control Reference

Definition and UsageThe HorizontalAlign property is used to set or return horizontal alignment of the content in theTableCell control.

Syntax

<asp:TableCell HorizontalAlign="align" runat="server">Some Content</asp:TableCell>

Attribute Description

align Specifies the horizontal alignment of the content.

Possible values:

CenterJustifyLeftNotSet (Default)Right

Example

The following example sets the HorizontalAlign property of a TableCell control:

<form runat="server"><asp:Table id="tab1" runat="server"><asp:TableRow><asp:TableCell HorizontalAlign="Center">Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 360: ASP.Net

ASP.NET RowSpan Property

Complete TableCell Control Reference

Definition and UsageThe RowSpan property is used to set or return number of rows the TableCell spans in a Table control.

Syntax

<asp:TableCell RowSpan="num" runat="server">Some content</asp:TableCell>

Attribute Description

num Specifies the number of rows the TableCell spans

Example

The following example sets the RowSpan mode to "2":

<form runat="server"><asp:Table id="tab1" runat="server">

<asp:TableRow><asp:TableCell RowSpan="2">Some Content</asp:TableCell><asp:TableCell>Some Content</asp:TableCell></asp:TableRow>

<asp:TableRow><asp:TableCell>Some Content</asp:TableCell></asp:TableRow>

</asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 361: ASP.Net

ASP.NET Text Property

Complete TableCell Control Reference

Definition and UsageThe Text property is used to set or return the text of a TableCell control.

Syntax

<asp:TableCell Text="string" runat="server" />

Attribute Description

string A string that specifies the text of the Table cell

Example

The following example sets the text of a TableCell control:

<form runat="server"><asp:Table id="tab1" runat="server"><asp:TableRow><asp:TableCell Text="Hello" /></asp:TableRow></asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 362: ASP.Net

ASP.NET VerticalAlign Property

Complete TableCell Control Reference

Definition and UsageThe VerticalAlign property is used to set or return vertical alignment of the content in the TableCellcontrol.

Syntax

<asp:TableCell VerticalAlign="align" runat="server">Some Content</asp:TableCell>

Attribute Description

align Specifies the vertical alignment of the content.

Possible values:

BottomMiddleNotSetTop

Example

The following example sets the VerticalAlign property of a TableCell control:

<form runat="server"><asp:Table id="tab1" runat="server"><asp:TableRow><asp:TableCell VerticalAlign="Center">Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 363: ASP.Net

ASP.NET Wrap Property

Complete TableCell Control Reference

Definition and UsageThe Wrap property is used to set or return whether or not the text within a table cell wraps.

Syntax

<asp:TableCell Wrap="True|False" runat="server">Some content</asp:TableCell>

Example

The following example sets the wrap mode to "False":

<form runat="server"><asp:Table id="tab1" runat="server">

<asp:TableRow><asp:TableCell Wrap="False">Some Content<asp:TableCell></asp:TableRow>

</asp:Table></form>

Show example »

Complete TableCell Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 364: ASP.Net

ASP.NET TableRow Control

Web Server Controls

Definition and UsageThe TableRow control is used in conjunction with the TableCell control and the Table control to create a row in a table.

Tip: The rows of a table are stored in the Rows collection of the Table control.

Properties

Property Description .NET

Cells

HorizontalAlign The horizontal alignment of the contents in the table row 1.0

TableSection The location of a TableRow object in a Table control 2.0

VerticalAlign The vertical alignment of the contents in the table row 1.0

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExamplesTableDeclare two Table controls in an .aspx file.

Table 2Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 365: ASP.Net

ASP.NET HorizontalAlign Property

Complete TableRow Control Reference

Definition and UsageThe HorizontalAlign property is used to set or return horizontal alignment of the content in theTableRow control.

Syntax

<asp:TableRow HorizontalAlign="align" runat="server">Some Content</asp:TableRow>

Attribute Description

align Specifies the horizontal alignment of the content.

Possible values:

CenterJustifyLeftNotSet (Default)Right

Example

The following example sets the HorizontalAlign property of a TableRow control:

<form runat="server"><asp:Table id="tab1" runat="server"><asp:TableRow HorizontalAlign="Right"><asp:TableCell>Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete TableRow Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 366: ASP.Net

ASP.NET TableSection Property

Complete TableRow Control Reference

Definition and UsageThe TableSection property is used to set or return location for a TableRow object in a Table control.

This property to get or set where the TableRow object is placed in a Table control.

Syntax

<asp:TableRow TableSection="section" runat="server">Some Content</asp:TableRow>

Attribute Description

section Specifies which table section the row belongs to.

Possible values:

TableHeader - Header rowTableBody - Default. Body of the tableTableFooter - The footer row

Example

The following example sets the TableSection property of a TableRow control:

<form runat="server"><asp:table id="Table1" runat="server" GridLines="Both">

<asp:TableRow TableSection="TableHeader"><asp:TableCell>Header</asp:TableCell></asp:TableRow>

</asp:table></form>

Show example »

Complete TableRow Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 367: ASP.Net

ASP.NET VerticalAlign Property

Complete TableRow Control Reference

Definition and UsageThe VerticalAlign property is used to set or return vertical alignment of the content in the TableRowcontrol.

Syntax

<asp:TableRow VerticalAlign="align" runat="server">Some Content</asp:TableRow>

Attribute Description

align Specifies the vertical alignment of the content.

Possible values:

BottomMiddleNotSetTop

Example

The following example sets the VerticalAlign property of a TableRow control:

<form runat="server"><asp:Table id="tab1" runat="server"><asp:TableRow VerticalAlign="Middle"><asp:TableCell>Hello!</asp:TableCell><asp:TableCell>Hello!</asp:TableCell></asp:TableRow></asp:Table></form>

Show example »

Complete TableRow Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 368: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat=server><asp:Table runat="server" CellPadding="5"GridLines="horizontal" HorizontalAlign="Center"> <asp:TableRow> <asp:TableCell>1</asp:TableCell> <asp:TableCell>2</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>3</asp:TableCell> <asp:TableCell>4</asp:TableCell> </asp:TableRow></asp:Table><br /><asp:Table runat="server" CellPadding="5"GridLines="vertical" HorizontalAlign="Center"> <asp:TableRow> <asp:TableCell>1</asp:TableCell> <asp:TableCell>2</asp:TableCell> </asp:TableRow> <asp:TableRow> <asp:TableCell>3</asp:TableCell> <asp:TableCell>4</asp:TableCell> </asp:TableRow></asp:Table></form>

</body></html>

1 2

3 4

1 2

3 4

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 369: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub Page_Load(sender As Object, e As EventArgs)dim rows,cells,j,irows=3cells=2For j=0 To rows-1 dim r As New TableRow() For i=0 To cells-1 dim c As New TableCell() c.Controls.Add(New LiteralControl("row " & j & ", cell " & i)) r.Cells.Add(c) Next Table1.Rows.Add(r)NextEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:Table id="Table1" BorderWidth="1" GridLines="Both"runat="server" /></form>

</body></html>

row 0, cell 0 row 0, cell 1row 1, cell 0 row 1, cell 1row 2, cell 0 row 2, cell 1

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 370: ASP.Net

ASP.NET TextBox Control

Web Server Controls

Definition and UsageThe TextBox control is used to create a text box where the user can input text.

Properties

Property Description .NET

AutoCompleteType Specifies the AutoComplete behavior of a TextBox 2.0

AutoPostBack A Boolean value that specifies whether the control isautomatically posted back to the server when the contentschange or not. Default is false

1.0

CausesValidation Specifies if a page is validated when a Postback occurs 2.0

Columns The width of the textbox 1.0

MaxLength The maximum number of characters allowed in the textbox 1.0

ReadOnly Specifies whether or not the text in the text box can bechanged

1.0

Rows The height of the textbox (only used if TextMode="Multiline") 1.0

runat Specifies that the control is a server control. Must be set to"server"

TagKey

Text The contents of the textbox 1.0

TextMode Specifies the behavior mode of a TextBox control (SingleLine,MultiLine or Password)

1.0

ValidationGroup The group of controls that is validated when a Postback occurs

Wrap A Boolean value that indicates whether the contents of thetextbox should wrap or not

1.0

OnTextChanged The name of the function to be executed when the text in thetextbox has changed

Web Control Standard Properties

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth,CssClass, Enabled, Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID,Style, TabIndex, ToolTip, Width

For a full description, go to Web Control Standard Attributes.

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExamplesTextboxDeclare one TextBox control, one Button control, and one Label control in an .aspx file. When thesubmit button is triggered, the submit subroutine is executed. The submit subroutine writes a text tothe Label control.

Textbox 2Declare one TextBox control, one Button control, and one Label control in an .aspx file. When thesubmit button is triggered, the submit subroutine is executed. The submit subroutine copies thecontents of the textbox to the Label control.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 371: ASP.Net

ASP.NET AutoCompleteType Property

Complete TextBox Control Reference

Definition and UsageThe AutoCompleteType property is used to set or return the AutoComplete category of a TextBox control.

The AutoComplete feature creates a list of values entered in a text box. When using the text box again, a list of values entered is displayed. The user canthen select a value instead of retyping a previously entered value

Syntax

<asp:TextBox AutoCompleteType="cat" runat="server"/>

Attribute Description

cat Specifies the AutoComplete category.

Possible values:

BusinessCity - City in the business categoryBusinessCountryRegion - Country/region in the business categoryBusinessFax - Fax number in the business categoryBusinessPhone - Phone number in the business categoryBusinessState - State in the business categoryBusinessStreetAddress - Street address in the business categoryBusinessUrl - Web site URL in the business categoryBusinessZipCode - ZIP code in the business categoryCellular - Phone number in the mobile-phone categoryCompany - Business name in the business categoryDepartment - Department in the business categoryDisabled - AutoComplete feature is disabledDisplayName - Name to display in the user categoryEmail - E-mail in the user categoryFirstName - First name in the user categoryGender - Gender in the user categoryHomeCity - Home city in the user categoryHomeCountryRegion - Home country/region in the user categoryHomeFax - Fax number in the user categoryHomepage - Web site URL in the user categoryHomePhone - Phone number in the user categoryHomeState - Home state in the user categoryHomeStreetAddress - Home street in the user categoryHomeZipCode - ZIP code in the user categoryJobTitle - Job title in the user categoryLastName - Last name in the user categoryMiddleName - Middle name in the user categoryNone - No category specifiedNotes - Extra information in the formOffice - Office location in the business categoryPager - Phone number in the pager categorySearch - Keywords in the search category

Example

The following example sets the AutoCompleteType mode to "FirstName":

<form runat="server"><asp:TextBox id="tb1" runat="server" AutoCompleteType="FirstName" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 372: ASP.Net

ASP.NET AutoPostBack Property

Complete TextBox Control Reference

Definition and UsageThe AutoPostBack property is used to set or return whether or not an automatic post back occurs whenthe user presses "ENTER" or "TAB" in the TextBox control.

If this property is set to TRUE the automatic post back is enabled, otherwise FALSE. Default is FALSE.

Syntax

<asp:TextBox AutoPostBack="TRUE|FALSE" runat="server"/>

Example

The following example sets the AutoPostBack mode to "TRUE":

<form runat="server"><asp:TextBox id="tb1" runat="server" AutoPostBack="TRUE" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 373: ASP.Net

ASP.NET Columns Property

Complete TextBox Control Reference

Definition and UsageThe Columns property is used to set or return the width of the TextBox control.

Syntax

<asp:TextBox Columns="num" runat="server" />

Attribute Description

num A number specifying the width, in characters, of the text box

Example

The following example sets the width of a TextBox control:

<form runat="server"><asp:TextBox id="tb1" runat="server" Columns="50" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 374: ASP.Net

ASP.NET MaxLength Property

Complete TextBox Control Reference

Definition and UsageThe MaxLength property is used to set or return the maximum number of characters allowed in aTextBox control.

Syntax

<asp:TextBox MaxLength="num" runat="server" />

Attribute Description

num A number specifying the maximum number of characters allowed in the text box

Example

The following example sets the max number of characters allowed in a TextBox control:

<form runat="server"><asp:TextBox id="tb1" runat="server" MaxLength="10" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 375: ASP.Net

ASP.NET ReadOnly Property

Complete TextBox Control Reference

Definition and UsageThe ReadOnly property is used to set or return whether or not the text in the TextBox control can bechanged.

If this property is set to TRUE the text can not be changed, otherwise FALSE. Default is FALSE.

Syntax

<asp:TextBox ReadOnly="TRUE|FALSE" runat="server"/>

Example

The following example sets the ReadOnly mode to "TRUE":

<form runat="server"><asp:TextBox id="tb1" runat="server" ReadOnly="TRUE"Text="This text is read only" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 376: ASP.Net

ASP.NET Rows Property

Complete TextBox Control Reference

Definition and UsageThe Rows property is used to set or return the height of the TextBox control.

This property can only be used if TextMode="Multiline"

Syntax

<asp:TextBox runat="server" Rows="num" TextMode="MultiLine" />

Attribute Description

num A number specifying the height, in rows, of the text box

Example

The following example sets the height of a TextBox control:

<form runat="server"><asp:TextBox id="tb1" runat="server"TextMode="MultiLine" Rows="5" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 377: ASP.Net

ASP.NET Text Property

Complete TextBox Control Reference

Definition and UsageThe Text property is used to set or return the text of a TextBox control.

Syntax

<asp:TextBox Text="string" runat="server" />

Attribute Description

string A string that specifies the text of the TextBox control

Example

The following example sets the text of a TextBox control:

<form runat="server"><asp:TextBox id="tb1" runat="server" Text="Name" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 378: ASP.Net

ASP.NET TextMode Property

Complete TextBox Control Reference

Definition and UsageThe TextMode property is used to set or return the behavior mode of a TextBox control.

Syntax

<asp:TextBox TextMode="mode" runat="server" />

Attribute Description

mode A number specifying the maximum number of characters allowed in the text box

Possible values:

SingleLine - Default. One line text boxMultiLine - Text box with multiple linesPassword - One line text box that masks the input

Example

The following example sets the text mode of a TextBox control to "Password":

<form runat="server"><asp:TextBox id="tb1" runat="server" TextMode="Password" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 379: ASP.Net

ASP.NET Wrap Property

Complete TextBox Control Reference

Definition and UsageThe Wrap property is used to set or return whether or not the text content wraps within a multilinetext box.

This property can only be used if TextMode="Multiline"

Syntax

<asp:TextBox Wrap="TRUE|FALSE" TextMode="MultiLine" runat="server"/>

Example

The following example sets the wrap mode to "False":

<form runat="server"><asp:TextBox id="tb1" runat="server"TextMode="MultiLine" Wrap="False" /></form>

Show example »

Complete TextBox Control Reference

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 380: ASP.Net

ASP Source: Output Result:

<script runat="server">Sub submit(sender As Object, e As EventArgs) lbl1.Text="Your name is " & txt1.TextEnd Sub</script>

<!DOCTYPE html><html><body>

<form runat="server">Enter your name:<asp:TextBox id="txt1" runat="server" /><asp:Button OnClick="submit" Text="Submit" runat="server" /><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Enter your name:

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 381: ASP.Net

ASP Source: Output Result:

<script runat="server">sub submit(sender As Object, e As EventArgs)lbl1.Text=txt1.Textend sub</script>

<!DOCTYPE html><html><body>

<form runat="server"><asp:TextBox id="txt1" Text="Hello World!"Font_Face="verdana" BackColor="#0000ff"ForeColor="white" TextMode="MultiLine"Height="50" runat="server" /><asp:Button OnClick="submit"Text="Copy Text to Label" runat="server" /><p><asp:Label id="lbl1" runat="server" /></p></form>

</body></html>

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 382: ASP.Net

ASP.NET XML Control

Web Server Controls

Definition and UsageThe XML control is used to display an XML document or the results of an XSL Transform.

Note: At least one of the XML Document properties must be set or no XML document is displayed.

You can also specify an XSLT document that will format the XML document before it is written to theoutput. You can format the XML document with the Transform property or the TransformSourceproperty.

Properties

Property Description .NET

ClientID

Controls

Document Deprecated. Specifies an XML document using aSystem.Xml.XmlDocument object

1.0

DocumentContent Specifies an XML string 1.0

DocumentSource Specifies a path to an XML file to display 1.0

EnableTheming

runat Specifies that the control is a server control. Must be set to"server"

1.0

SkinID

Transform Formats the XML document using aSystem.Xml.Xsl.XslTransform object

1.0

TransformArgumentList

TransformSource Specifies a path to an XSL Transform file

XPathNavigator

Control Standard Properties

AppRelativeTemplateSourceDirectory, BindingContainer, ClientID, Controls,EnableTheming, EnableViewState, ID, NamingContainer, Page, Parent, Site,TemplateControl, TemplateSourceDirectory, UniqueID, Visible

For a full description, go to Control Standard Attributes.

ExampleXMLHow to use the Xml control to display the result of an XSL Transform.

Web Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 383: ASP.Net

XML DocumentSource Property

XML Control

Definition and UsageThe DocumentSource property is used to set or return the path to an XML document to display in theXml control.

Syntax

<asp:Xml DocumentSource="path" runat="server" />

Attribute Description

path A string that specifies the location of the xml file.

This attribute can be the relative or absolute path:

Relative path: The path of the file relative to the location of the currentweb page (like "~/note.xml")Absolute path: The absolute path (like "C:\xml\note.xml")

Example

Example

The following example specifies the XML document used:

<form runat="server"><asp:Xml id="xml1" runat="server" DocumentSource="note.xml" /></form>

Show example »

The XML file used in this example is "note.xml"

XML Control

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 384: ASP.Net

ASP Source: Output Result:

<!DOCTYPE html><html><body>

<form runat="server"><asp:Xml DocumentSource="cdcatalog.xml"TransformSource="cdcatalog.xsl" runat="server" /></form>

<p><a href="cdcatalog.xml" target="_blank">View XMLfile</a></p><p><a href="cdcatalog.xsl" target="_blank">View XSLfile</a></p>

</body></html>

My CD Collection

Title ArtistEmpire Burlesque Bob DylanHide your heart Bonnie TylerGreatest Hits Dolly PartonStill got the blues Gary MooreEros Eros Ramazzotti

View XML file

View XSL file

Copyright: W3Schools.com

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 385: ASP.Net

« Previous Next Chapter »

ASP.NET Web Forms - Validation Controls

Validation server controls are used to validate user-input.

Validation Server ControlsA Validation server control is used to validate the data of an input control. If the data does not passvalidation, it will display an error message to the user.

The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

Validation Server Control Description

CompareValidator Compares the value of one input control to the value ofanother input control or to a fixed value

CustomValidator Allows you to write a method to handle the validation of thevalue entered

RangeValidator Checks that the user enters a value that falls between twovalues

RegularExpressionValidator Ensures that the value of an input control matches aspecified pattern

RequiredFieldValidator Makes an input control a required field

ValidationSummary Displays a report of all validation errors occurred in a Webpage

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 386: ASP.Net

ASP.NET CompareValidator Control

Validation Server Controls

Definition and UsageThe CompareValidator control is used to compare the value of one input control to the value of anotherinput control or to a fixed value.

Note: If the input control is empty, the validation will succeed. Use the RequiredFieldValidator controlto make the field required.

Properties

Property Description

BackColor The background color of the CompareValidator control

ControlToCompare The name of the control to compare with

ControlToValidate The id of the control to validate

Display The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the errormessage only in the ValidationSummary control)Static (the control displays an error message if validation fails.Space is reserved on the page for the message even if the inputpasses validation.Dynamic (the control displays an error message if validationfails. Space is not reserved on the page for the message if theinput passes validation

EnableClientScript A Boolean value that specifies whether client-side validation is enabledor not

Enabled A Boolean value that specifies whether the validation control isenabled or not

ErrorMessage The text to display in the ValidationSummary control when validationfails. Note: This text will also be displayed in the validation control ifthe Text property is not set

ForeColor The foreground color of the control

id A unique id for the control

IsValid A Boolean value that indicates whether the control specified byControlToValidate is determined to be valid

Operator The type of comparison to perform. The operators are:

EqualGreaterThanGreaterThanEqualLessThanLessThanEqualNotEqualDataTypeCheck

runat Specifies that the control is a server control. Must be set to "server"

Text The message to display when validation fails

Type Specifies the data type of the values to compare. The types are:

CurrencyDateDoubleIntegerString

ValueToCompare A specified value to compare with

ExamplesCompareValidatorDeclare two TextBox controls, one Button control, and one CompareValidator control in an .aspx file. Ifvalidation fails, the text "Validation Failed!" will be displayed in red on a yellow background in theCompareValidator control.

CompareValidator 2Declare two TextBox controls, one ListBox control, one Button control, and one CompareValidatorcontrol in an .aspx file. The check_operator() function sets the operator of the CompareValidatorcontrol equal to the selected operator in the ListBox control, then it validates the CompareValidatorcontrol. If validation fails, the text "Validation Failed!" will be displayed in red on a yellow background inthe CompareValidator control.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 387: ASP.Net

ASP.NET CustomValidator Control

Validation Server Controls

Definition and UsageThe CustomValidator control allows you to write a method to handle the validation of the valueentered.

Properties

Property Description

BackColor The background color of the CustomValidator control

ClientValidationFunction Specifies the name of the client-side validation script function to beexecuted. Note: The script must be in a language that the browsersupports, such as VBScript or JScript

With VBScript, the function must be in the form:

Sub FunctionName (source, arguments)

With JScript, the function must be in the form:

Function FunctionName (source, arguments)

ControlToValidate The id of the control to validate

Display The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the errormessage only in the ValidationSummary control)Static (the control displays an error message if validation fails.Space is reserved on the page for the message even if the inputpasses validation.Dynamic (the control displays an error message if validationfails. Space is not reserved on the page for the message if theinput passes validation

EnableClientScript A Boolean value that specifies whether client-side validation is enabledor not

Enabled A Boolean value that specifies whether the validation control isenabled or not

ErrorMessage The text to display in the ValidationSummary control when validationfails. Note: This text will also be displayed in the validation control ifthe Text property is not set

ForeColor The foreground color of the control

id A unique id for the control

IsValid A Boolean value that indicates whether the control specified byControlToValidate is determined to be valid

OnServerValidate Specifies the name of the server-side validation script function to beexecuted

runat Specifies that the control is a server control. Must be set to "server"

Text The message to display when validation fails

ExampleCustomValidatorDeclare two Label controls, one TextBox control, one Button control, and one CustomValidator controlin an .aspx file. The user() function checks the length of the input value. If the length is <8 or >16 thetext "A username must be between 8 and 16 characters!" will appear in the CustomValidator control.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 388: ASP.Net

ASP.NET RangeValidator Control

Validation Server Controls

Definition and UsageThe RangeValidator control is used to check that the user enters an input value that falls between twovalues. It is possible to check ranges within numbers, dates, and characters.

Note: The validation will not fail if the input control is empty. Use the RequiredFieldValidator control tomake the field required.

Note: The validation will not fail if the input value cannot be converted to the data type specified. Usethe CompareValidator control, with its Operator property set toValidationCompareOperator.DataTypeCheck, to verify the data type of the input value.

Properties

Property Description

BackColor The background color of the RangeValidator control

ControlToValidate The id of the control to validate

Display The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the error messageonly in the ValidationSummary control)Static (the control displays an error message if validation fails. Spaceis reserved on the page for the message even if the input passesvalidation.Dynamic (the control displays an error message if validation fails.Space is not reserved on the page for the message if the inputpasses validation

EnableClientScript A Boolean value that specifies whether client-side validation is enabled ornot

Enabled A Boolean value that specifies whether the validation control is enabled ornot

ErrorMessage The text to display in the ValidationSummary control when validation fails.Note: This text will also be displayed in the validation control if the Textproperty is not set

ForeColor The foreground color of the control

id A unique id for the control

IsValid A Boolean value that indicates whether the control specified byControlToValidate is determined to be valid

MaximumValue Specifies the maximum value of the input control

MinimumValue Specifies the minimum value of the input control

runat Specifies that the control is a server control. Must be set to "server"

Type Specifies the data type of the value to check. The types are:

CurrencyDateDoubleIntegerString

Text The message to display when validation fails

ExamplesRangeValidatorDeclare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. Ifvalidation fails, the text "The date must be between 1/1/2002 and 31/5/2002!" will be displayed in theRangeValidator control.

RangeValidator 2Declare one TextBox control, one Button control, one Label control, and one RangeValidator control inan .aspx file. The submit() function checks if the page is valid. If it is valid, it returns "The page isvalid!" in the Label control. If it is not valid, it returns "The page is not valid!" in the Label control. Ifvalidation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidatorcontrol.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 389: ASP.Net

ASP.NET RegularExpressionValidator Control

Validation Server Controls

Definition and UsageThe RegularExpressionValidator control is used to ensure that an input value matches a specifiedpattern.

Note: Both server- and client-side validation are performed unless the browser does not supportclient-side validation or the EnableClientScript property is set to false.

Note: The validation will not fail if the input control is empty. Use the RequiredFieldValidator control tomake the field required.

Properties

Property Description

BackColor The background color of the RegularExpressionValidator control

ControlToValidate The id of the control to validate

Display The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the errormessage only in the ValidationSummary control)Static (the control displays an error message if validation fails.Space is reserved on the page for the message even if the inputpasses validation.Dynamic (the control displays an error message if validationfails. Space is not reserved on the page for the message if theinput passes validation

EnableClientScript A Boolean value that specifies whether client-side validation is enabledor not

Enabled A Boolean value that specifies whether the validation control isenabled or not

ErrorMessage The text to display in the ValidationSummary control when validationfails. Note: This text will also be displayed in the validation control ifthe Text property is not set

ForeColor The foreground color of the control

id A unique id for the control

IsValid A Boolean value that indicates whether the control specified byControlToValidate is determined to be valid

runat Specifies that the control is a server control. Must be set to "server"

BackColor The background color of the RegularExpressionValidator control

Text The message to display when validation fails

ValidationExpression Specifies the expression used to validate input control. The expressionvalidation syntax is different on the client than on the server. JScript isused on the client. On the server, the language you have specified isused

ExampleRegularExpressionValidatorDeclare one TextBox control, one Button control, one Label control, and oneRegularExpressionValidator control in an .aspx file. The submit() function checks if the page is valid. Ifit is valid, it returns "The page is valid!" in the Label control. If it is not valid, it returns "The page isnot valid!" in the Label control. If validation fails, the text "The zip code must be 5 numeric digits!" willbe displayed in the RegularExpressionValidator control.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 390: ASP.Net

ASP.NET RequiredFieldValidator Control

Validation Server Controls

Definition and UsageThe RequiredFieldValidator control is used to make an input control a required field.

With this control, the validation fails if the input value does not change from its initial value. By default,the initial value is an empty string ("").

Note: Leading and trailing spaces of the input value are removed before validation.

Note: The InitialValue property does not set the default value for the input control. It indicates thevalue that you do not want the user to enter in the input control.

Properties

Property Description

BackColor The background color of the RequiredFieldValidator control

ControlToValidate The id of the control to validate

Display The display behavior for the validation control. Legal values are:

None (the control is not displayed. Used to show the errormessage only in the ValidationSummary control)Static (the control displays an error message if validation fails.Space is reserved on the page for the message even if the inputpasses validation.Dynamic (the control displays an error message if validationfails. Space is not reserved on the page for the message if theinput passes validation

EnableClientScript A Boolean value that specifies whether client-side validation is enabledor not

Enabled A Boolean value that specifies whether the validation control isenabled or not

ErrorMessage The text to display in the ValidationSummary control when validationfails. Note: This text will also be displayed in the validation control ifthe Text property is not set

ForeColor The foreground color of the control

id A unique id for the control

InitialValue Specifies the starting value of the input control. Default value is ""

IsValid A Boolean value that indicates whether the control specified byControlToValidate is determined to be valid

runat Specifies that the control is a server control. Must be set to "server"

Text The message to display when validation fails

ExampleRequiredFieldValidatorDeclare two TextBox controls, one Button control, and one RequiredFieldValidator control in an .aspxfile. It shows how to use the RequiredFieldValidator control to make the "txt_name" textbox a requiredfield.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com

Page 391: ASP.Net

ASP.NET ValidationSummary Control

Validation Server Controls

Definition and UsageThe ValidationSummary control is used to display a summary of all validation errors occurred in a Webpage.

The error message displayed in this control is specified by the ErrorMessage property of each validationcontrol. If the ErrorMessage property of the validation control is not set, no error message is displayedfor that validation control.

Properties

Property Description

DisplayMode How to display the summary. Legal values are:

BulletListListSingleParagraph

EnableClientScript A Boolean value that specifies whether client-side validation is enabled ornot

Enabled A Boolean value that specifies whether the validation control is enabled ornot

ForeColor The fore color of the control

HeaderText A header in the ValidationSummary control

id A unique id for the control

runat Specifies that the control is a server control. Must be set to "server"

ShowMessageBox A Boolean value that specifies whether the summary should be displayed ina message box or not

ShowSummary A Boolean value that specifies whether the ValidationSummary controlshould be displayed or hidden

ExamplesValidationsummaryUse the ValidationSummary control to write a bulleted list of fields that are required but left empty bythe user.

Validationsummary 2Use the ValidationSummary control to display a message box of the fields that are required but leftempty by the user.

Validation Server Controls

Created by www.ebooktutorials.blogspot.in

Content Downloaded from www.w3schools.com