Professional Documents
Culture Documents
ASP Net
ASP Net
in
ASP.Net Full
Tutorial
(ASP.Net Web Pages,ASP.Net MVC,ASP.Net Web Forms)
Created by www.ebooktutorials.blogspot.in
ASP.NET
Previous
Next Chapter
ASP.NET
ASP.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 the
browser as plain HTML.
ASP.NET Razor
Razor 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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Created by www.ebooktutorials.blogspot.in
The Web Platform Installer also makes it easy to install popular free web applications for blogging, content management and more with a built-in Windows
Web Application Gallery.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
W3Schools.com
Next Chapter
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
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.
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
<!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:
WebMatrix starts a web server (IIS Express) and runs the page on your computer. The page is displayed in your default browser:
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Create
Create
Create
Create
Create
2. Create Folders
In the folder named "Demo" (your website), create 5 folders:
Account - for storing login and membership files
App_Data - for storing databases and data files
Images - for storing images
Scripts - for storing browser scripts
Shared - for storing shared style and layout files
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
Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/Shared/Site.css" />
</head>
<body>
<div id="main">
@RenderBody()
<p>© 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.
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.
Congratulations
You have created your first web site, with a main page (the Default page), a common template for all
your 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 a
database, and finally we will add login and security.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Add a PageStart page
Add an about page
Add a navigation menu
_PageStart.cshtml
@{
// Set the layout page for the whole site
Layout = "~/Shared/Layout.cshtml";
}
The _PageStart file above contains code to be run in every page of the web site. After adding this, you
no longer need to add the layout information to every web page.
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.
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>© 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 unordered
list (marked red).
Created by www.ebooktutorials.blogspot.in
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 an
unordered list (marked red).
Default.cshtml
<h1>Welcome to Us</h1>
<p>
Lorem Ipsum Porem Lorem Ipsum Porem
</p>
Run example
Congratulations
You have added navigation to your website.
In the next chapter we will add a database.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Create a database
Add data to the database
Create a page to list the 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 Database
WebMatrix 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
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)
Created by www.ebooktutorials.blogspot.in
Right-click the Product table and then click Data.
In the edit pane, enter the following records:
Name
Description
Price
Bread
2.99
Strawberry Cake
9.99
Apple Pie
12.99
Pecan Pie
10.99
Lemon Pie
11.99
Cupcakes
7.99
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>
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 Connection
The 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 user
name and password.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Create a WebSecurity database to hold user profiles and membership information
Initialize WebSecurity in AppStart
Add a membership registration page
Add a member login page
_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 WebSecurity
database (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 created
automatically if they don't exist. Otherwise set to false.
Although true indicates that the membership tables can be created automatically, the
database itself must always exist.
Site.css
/* Forms --------------------*/
fieldset label
{
display:block;
padding:4px;
Created by www.ebooktutorials.blogspot.in
}
input[type="text"],input[type="password"]
{
width:300px;
}
input[type="submit"]
{
padding:4px;
}
Register.cshtml
@{// Initialize page
var email = "";
var password = "";
var confirmPassword = "";
var ErrorMessage = "";
// If this is a POST request, validate and process data
if (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 account
if (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 exit
Response.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>
Login.cshtml
@{// Initialize page
var username = "";
Created by www.ebooktutorials.blogspot.in
var password = "";
var ErrorMessage = "";
// If this is a POST request, validate and process data
if (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 exit
if (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>
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>© 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 Login
pages added to the navigation menu (marked red).
Congratulations
You have added membership registration and login information to your website.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Add access restriction security to a web 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.
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 marked
red.
Congratulations
You 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
ASP.NET is a development framework for building web pages and
web 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:
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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
In this tutorial we will use Razor markup with C# and Visual Basic code
What is Razor?
Razor
Razor
Razor
Razor
<!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 the
default)
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
Created by www.ebooktutorials.blogspot.in
Inline expressions (variables and functions) start with @
Variables are declared with the Dim keyword
Strings are enclosed with quotation marks
VB code is not case sensitive
VB files have the extension .vbhtml
Example
<!-- Single statement block -->
@Code dim myMessage = "Hello World" End Code
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
With Web Pages it is easy to create a web site with a consistent layout.
A Consistent Look
On the Internet you will discover many web sites with a consistent look and feel:
Every page have the same header
Every page have the same footer
Every 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 Blocks
Many 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 you
change 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
Layout Page:
<html>
<body>
<p>This is header text</p>
@RenderBody()
<p>© 2012 W3Schools. All rights reserved.</p>
</body>
</html>
Created by www.ebooktutorials.blogspot.in
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 web
applications much more manageable and easier to maintain.
_AppStart.cshtml
@{
WebMail.SmtpServer = "mailserver.example.com";
WebMail.EnableSsl = true;
WebMail.UserName = "username@example.com";
WebMail.Password = "your-password";
WebMail.From = "your-name-here@example.com";
}
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The
The
The
The
The
http://www.w3schools.com/html5/html5_intro.asp
w3schools
/html5/html5_intro.asp
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 ~ Operator
To 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:
Created by www.ebooktutorials.blogspot.in
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):
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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 requested
page.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
A form is a section of an HTML document where you put input controls (text boxes, check boxes, radio buttons, and pull-down lists)
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 explained
The 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 stores
it in the variable imagePath.
Created by www.ebooktutorials.blogspot.in
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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
@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 {
Description
href
RenderBody()
Renders the portion of a content page that is not within a named section (In layout pages)
RenderPage(page)
RenderSection(section)
Write(object)
WriteLitteral
Description
isPost
Returns true if the HTTP data transfer method used by the client is a POST request
Layout
Page
Provides property-like access to data shared between pages and layout pages
Request
Server
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
</html
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Persons.txt
George,Lucas
Steven,Spielberg
Alfred,Hitchcock
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> </text>}
<br />
}
</body>
</html>
Run example
Example explained
Server.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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Web Helpers greatly simplifies web development and common programming tasks.
ASP.NET Helpers
ASP.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 Chart helper can display data from arrays , from databases, or from files.
Installing Helpers
Some 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 the
ASP.NET Web Helpers Library.
If you have a web site created in WebMatrix, use the following procedure to install helpers:
1.
2.
3.
4.
5.
(* the first time you use Web Pages Administration, it will prompt you to create a password)
Created by www.ebooktutorials.blogspot.in
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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
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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The data you display in a chart can be from an array, from a database, or from data in a file.
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
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
- 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 and
data 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
_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 = "support@example.com";
WebMail.Password = "password-goes-here";
WebMail.From = "john@example.com";
}
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).
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.
Created by www.ebooktutorials.blogspot.in
Then create the page that will be used to send the email, and name it Email_Send:
Email_Send.cshtml
@{ // Read input
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
try
{
// Send email
WebMail.Send(to:"someone@example.com", 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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
index.php
<!DOCTYPE html>
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
Run the file and see PHP at work.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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>
Created by www.ebooktutorials.blogspot.in
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Examples in C#
Examples in VB
Examples Explained
Examples Explained
Basic C#
Basic VB
For Loop
For Each Loop
While Loop
Array
For Loop
For Each Loop
While Loop
Array
If Condition
If Else Condition
Else If Condition
Switch Condition
If Condition
If Else Condition
Else If Condition
Select Condition
Examples Explained
Examples Explained
Examples Explained
Examples Explained
Display
Display
Display
Display
Display
Display
Display
Display
a
a
a
a
Examples Explained
Previous
a
a
a
a
Examples Explained
Next Chapter
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
<h1>Hello Web Pages</h1>
<p>The time is @DateTime.Now</p>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
@RenderPage("header.cshtml")
<h1>Hello Web Pages</h1>
<p>This is a paragraph</p>
@RenderPage("footer.cshtml")
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
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>
Copyright: W3Schools.com
Company Name:
Contact Name:
Submit
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
<h1>Hello Web Pages</h1>
<p>The time is @DateTime.Now</p>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
@RenderPage("header.vbhtml")
<h1>Hello Razor</h1>
<p>This is a paragraph</p>
@RenderPage("footer.vbhtml")
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
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
Copyright: W3Schools.com
Company Name:
Contact Name:
Submit
Created by www.ebooktutorials.blogspot.in
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
Source:
Output Result:
<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>
Copyright: W3Schools.com
ALL_HTTP
ALL_RAW
APPL_MD_PATH
APPL_PHYSICAL_PATH
AUTH_PASSWORD
AUTH_TYPE
AUTH_USER
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTPS
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID
INSTANCE_META_PATH
LOCAL_ADDR
LOGON_USER
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE HOST
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
@{
var i = 0;
while (i < 5)
{
i += 1;
<p>Line @i</p>
}
}
</body>
</html>
Copyright: W3Schools.com
Line 1
Line 2
Line 3
Line 4
Line 5
Created by www.ebooktutorials.blogspot.in
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>
Members
Jani
Hege
Kai
Jim
The number of names in Members are 4
The person at position 2 is Hege
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high</p>
}
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@{var price=25;}
<html>
<body>
if (price>=30)
{
<p>The price is high.</p>
}
elseif(price>20 && price<30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
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>
Copyright: W3Schools.com
Today is Sunday
Created by www.ebooktutorials.blogspot.in
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
Source:
Output Result:
<html>
<body>
<ul>
@for each x in Request.ServerVariables
@<li>@x</li>
next x
</ul>
</body>
</html>
Copyright: W3Schools.com
ALL_HTTP
ALL_RAW
APPL_MD_PATH
APPL_PHYSICAL_PATH
AUTH_PASSWORD
AUTH_TYPE
AUTH_USER
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTPS
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID
INSTANCE_META_PATH
LOCAL_ADDR
LOGON_USER
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE HOST
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
<html>
<body>
@Code
Dim i=0
Do While i < 5
i += 1
@<p>Line @i</p>
Loop
End Code
</body>
</html>
Copyright: W3Schools.com
Line 1
Line 2
Line 3
Line 4
Line 5
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim members as String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=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>
Members
Jani
Hege
Kai
Jim
The number of names in Members are 4
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim price=50
End Code
<html>
<body>
@If price>30 Then
@<p>The price is too high.</p>
End If
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim price=20
End 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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim price=25
End Code
<html>
<body>
@if price>=30 Then
@<p>The price is high.</p>
ElseIfprice>20 And price<30 then
@<p>The price is OK.</p>
Else
@<p>The price is low.</p>
End If
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim weekday=DateTime.Now.DayOfWeek
Dim day=weekday.ToString()
Dim message=""
End Code
<html>
<body>
@Select Case day
Case "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 " & day
End Select
<p>@message</p>
</body>
</html>
Copyright: W3Schools.com
Today is Sunday
Created by www.ebooktutorials.blogspot.in
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>
Copyright: W3Schools.com
Price
2.99
9.99
12.99
Created by www.ebooktutorials.blogspot.in
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 WebGrid
Helper</title>
</head>
<body>
<h1>Small Bakery Products</h1>
<div id="grid">
@grid.GetHtml()
</div>
</body>
</html>
Copyright: W3Schools.com
Name
Description
Price
Bread
Baked fresh every day
2,99
Pecan Pie
If you like pecans, this is for you
12,99
Strawberry Cake Made from organic strawberries
9,99
Lemon Pie
Made with the best lemons in the world 11,99
Cupcakes
Your kids will love yhese
7,99
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@Code
Dim 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>
@Code
Dim row
for 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>
Copyright: W3Schools.com
Price
2.99
9.99
12.99
Created by www.ebooktutorials.blogspot.in
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 WebGrid
Helper</title>
</head>
<body>
<h1>Small Bakery Products</h1>
<div id="grid">
@grid.GetHtml()
</div>
</body>
</html>
Copyright: W3Schools.com
Name
Description
Price
Bread
Baked fresh every day
2,99
Pecan Pie
If you like pecans, this is for you
12,99
Strawberry Cake Made from organic strawberries
9,99
Lemon Pie
Made with the best lemons in the world 11,99
Cupcakes
Your kids will love yhese
7,99
Created by www.ebooktutorials.blogspot.in
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
Source:
Output Result:
@{
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();
}
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Source:
Output Result:
@{
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();
}
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
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
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
Source:
Output Result:
@Code
Dim db = Database.Open("SmallBakery")
Dim dbdata = db.Query("SELECT Name, Price FROM
Product")
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
Source:
Output Result:
@Code
Dim db = Database.Open("SmallBakery")
Dim dbdata = db.Query("SELECT Name, Price FROM
Product")
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
Source:
Output Result:
@Imports System.Data
@Code
Dim 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
Next Chapter
Description
AsBool(), AsBool(true|false)
AsDateTime(), AsDateTime(value)
AsDecimal(), AsDecimal(value)
AsFloat(), AsFloat(value)
Converts a string value to a float. Returns 0.0 or the specified value if the
string does not represent a decimal value.
AsInt(), AsInt(value)
Html.Raw(value)
Returns true if the value can be converted from a string to the specified
type.
IsEmpty()
IsPost
Returns true if the request is a POST. (Initial requests are usually a GET.)
Layout
Contains data shared between the page, layout pages, and partial pages in
the current request. You can use the dynamic Page property to access the
same data, as in the following example:
RenderBody()
(Layout pages) Renders the content of a content page that is not in any
named 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).
(Layout pages) Renders a content section that has a name. Set required to
false to make a section optional.
Request.Cookies[key]
Request.Files[key]
Request.Form[key]
Gets data that was posted in a form (as strings). Request[key] checks both
the Request.Form and the Request.QueryString collections.
Request.QueryString[key]
Gets data that was specified in the URL query string. Request[key] checks
both the Request.Form and the Request.QueryString collections.
Request.Unvalidated(key)
Request.Unvalidated().QueryString|Form|Cookies|Headers[key]
Response.AddHeader(name, value)
Caches the page output for a specified time. Optionally set sliding to reset
the timeout on each page access and varyByParams to cache different
versions of the page for each different query string in the page request.
Response.Redirect(path)
Response.SetStatus(httpStatusCode)
Response.WriteBinary(data [, mimetype])
Writes the contents of data to the response with an optional MIME type.
Response.WriteFile(file)
@section(sectionName) { content }
Server.HtmlDecode(htmlText)
Server.HtmlEncode(text)
Server.MapPath(virtualPath)
Returns the server physical path for the specified virtual path.
Server.UrlDecode(urlText)
Server.UrlEncode(text)
Session[key]
Gets or sets a value that exists until the user closes the browser.
ToString()
UrlData[index]
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Description
Database.Execute(SQLstatement [, parameters]
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 a
named connection string from the Web.config file.
Database.OpenConnectionString(connectionString)
Database.Query(SQLstatement[, parameters])
Database.QuerySingle(SQLstatement [, parameters])
Database.QueryValue(SQLstatement [, parameters])
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
With the WebMail object you can easily send emails from a web page.
Description
The WebMail Object provides email for ASP.NET Web Pages using SMTP (Simple Mail Transfer Protocol).
Example
See an example in the chapter: Web Pages Email.
Description
SmtpServer
The name the SMTP server that will send the emails
SmtpPort
EnableSsl
UserName
Password
From
Description
Send()
Type
Description
to
String
subject
String
body
String
Parameter
Type
Description
from
String
cc
String
filesToAttach
Collection
Filenames
isBodyHtml
Boolean
additionalHeaders
Collection
Additional headers
Technical Data
Name
Value
Class
System.Web.Helpers.WebMail
Namespace
System.Web.Helpers
Assembly
System.Web.Helpers.dll
_AppStart.cshtml
Created by www.ebooktutorials.blogspot.in
@}
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 25;
WebMail.EnableSsl = false;
WebMail.UserName = "support@example.com";
WebMail.Password = "password";
WebMail.From = "john@example.com"
}
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.
support@example.com 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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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.
Description
Bing.SearchBox([boxWidth])
Passes a search to Bing. To specify the site to search and a title for the
search box, you can set the Bing.SiteUrl and Bing.SiteTitle properties.
Normally you set these properties in the _AppStart page.
Displays Bing search results in the page with optional formatting. To specify
the site to search and a title for the search box, you can set the Bing.SiteUrl
and Bing.SiteTitle properties. Normally you set these properties in the
_AppStart page.
Description
Initializes a chart.
Chart.AddLegend([title] [, name])
Description
Crypto.Hash(string [, algorithm])
Crypto.Hash(bytes [, algorithm])
Returns a hash for the specified data. The default algorithm is sha256.
Description
Description
FileUpload.GetHtml([initialNumberOfFiles] [, allowMoreFilesToBeAdded]
[, includeFormTag] [, addText] [, uploadText])
Description
GamerCard.GetHtml(gamerTag)
Description
Created by www.ebooktutorials.blogspot.in
Helper
Description
Json.Encode(object)
Json.Decode(string)
Converts a JSON-encoded input string to a data object that you can iterate
over or insert into a database.
Description
Renders social networking links using the specified title and optional URL.
Description
ModelStateDictionary.AddError(key, errorMessage)
Associates an error message with a form field. Use the ModelState helper to
access this member.
ModelStateDictionary.AddFormError(errorMessage)
ModelStateDictionary.IsValid
Returns true if there are no validation errors. Use the ModelState helper to
access this member.
Description
Renders the properties and values of an object and any child objects.
Description
ReCaptcha.PublicKey
ReCaptcha.PrivateKey
Sets public and private keys for the reCAPTCHA service. Normally you set
these properties in the _AppStart page.
ReCaptcha.Validate([, privateKey])
ServerInfo.GetHtml()
Description
Twitter.Profile(twitterUserName)
Twitter.Search(searchQuery)
Description
Renders a Flash video player for the specified file with optional width and
height.
Renders a Windows Media player for the specified file with optional width
and height.
Renders a Silverlight player for the specified .xap file with required width
and height.
Description
WebCache.Get(key)
Returns the object specified by key, or null if the object is not found.
WebCache.Remove(key)
Puts value into the cache under the name specified by key.
Description
WebGrid(data)
WebGrid.GetHtml()
Created by www.ebooktutorials.blogspot.in
WebGrid.Pager()
Description
WebImage(path)
WebImage.AddImagesWatermark(image)
WebImage.AddTextWatermark(text)
WebImage.FlipHorizontal()
WebImage.FlipVertical()
WebImage.GetImageFromRequest()
WebImage.Resize(width, height)
WebImage.RotateLeft()
WebImage.RotateRight()
WebImage.Save(path [, imageFormat])
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Description
The 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 change
passwords, and more.
Description
CurrentUserId
CurrentUserName
HasUserId
IsAuthenticated
Description
ChangePassword()
ConfirmAccount()
CreateAccount()
CreateUserAndAccount()
GeneratePasswordResetToken()
GetCreateDate()
GetPasswordChangeDate()
GetUserId()
InitializeDatabaseConnection()
IsConfirmed()
IsCurrentUser()
Login()
Logout()
RequireAuthenticatedUser()
RequireRoles()
Exits the page if the user is not a part of the specified roles
RequireUser()
ResetPassword()
UserExists()
Technical Data
Name
Value
Class
WebMatrix.WebData.WebSecurity
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
_AppStart.cshtml
@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId",
"Email", true);
}
The code above will run each time the web site (application) starts. It initializes the WebSecurity
database.
"Users" is the name of the WebSecurity database (Users.sdf).
Created by www.ebooktutorials.blogspot.in
"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 tables
should be created automatically if they don't exist, otherwise false.
Although true indicates automatic creation of the database tables, the database itself will not
be created automatically. It must exist.
john@johnson.net
peter@peterson.com
lars@larson.eut
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):
User Create
Id
Date
Confirmation Is
Last
Password
Token
Confirmed Password
Failure
NULL
12.04.2012
16:12:17
True
NULL
Password
Change
AFNQhWfy.... 12.04.2012
16:12:17
Note: If you want to see all columns and all content, open the database with WebMatrix and look inside
each table.
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Definition
The CurrentUserId property is the ID (primary key) for the current user in the WebSecurity
database.
C# and VB Syntax
WebSecurity.CurrentUserId
Examples
Example C#
@{
int value;
value=WebSecurity.CurrentUserId;
}
<p>Current User ID is: @value</p>
Example VB
@Code
Dim value as Integer
value=WebSecurity.CurrentUserId
End Code
<p>Current User ID is: @value</p>
Remarks
The 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 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
Definition
The 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
@Code
Dim value as String
value=WebSecurity.CurrentUserName
End Code
<p>Welcome @value</p>
Remarks
The CurrentUserName property is read only. It cannot be changed by code.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
Definition
The HasUserId property is a boolean value that indicates whether the current user has a user ID in
the 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
@Code
Dim value as Boolean
value=WebSecurity.HasUserId
End Code
<p>It is @value that the user has an ID</p>
Remarks
The 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 does
not 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.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
Definition
The IsAuthenticated property is a boolean value that indicates whether the current user is
authenticated (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
Remarks
The IsAuthenticated property is read only. It cannot be changed by code.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - ChangePassword()
WebSecurity Object
Definition
The 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
oldPassword
String
newPassword
String
Return Value
Type
Description
Boolean
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - ConfirmAccount()
WebSecurity Object
Definition
The 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
accountConfirmationToken String
Description
The confirmation tokene
Return Value
Type
Description
Boolean
Remarks
A confirmation token can be created by the CreateAccount(), CreateUserAndAccount(), or
GeneratePasswordResetToken() 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
Content Downloaded from www.w3schools.com
Created by www.ebooktutorials.blogspot.in
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - CreateAccount()
WebSecurity Object
Definition
The CreateAccount() method creates a new account in the user database, using user name and
password, 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
password
String
requireConfirmation
Boolean
Return Value
Type
Description
String
username is empty
username already has a membership account
password is empty
password is too long
database operation failed
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - CreateUserAndAccount()
WebSecurity Object
Definition
The CreateUserAndAccount() method creates a new account in the user database, using user name
and 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
password
String
propertyValues
Object
requireConfirmation
Boolean
Return Value
Type
Description
String
Remarks
The CreateUserAndAccount() method creates a new entry in the user profile table and then a
corresponding entry in the membership table in the WebSecurity database.
You can pass true for requireConfirmationToken parameter to require that the user account must
be confirmed by the user. To confirm the account, you get the token as the return value from the
CreateUserAndAccount() method.
If you are manually maintaining the user profile table and only want to create a membership table
entry for the user, call the CreateAccount() method instead.
username is empty
username already has a membership account
password is empty
password is too long
database operation failed
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - GeneratePasswordResetToken()
WebSecurity Object
Definition
The GeneratePasswordResetToken() method generates a password reset token that can be sent to
a user in email.
C# and VB Syntax
WebSecurity.GeneratePasswordResetToken(userName, expiration)
Parameters
Parameter
Type
Description
userName
String
expiration
Integer
Return Value
Type
Description
String
A reset token.
Remarks
Use 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 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="New
password" />
<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
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - GetCreateDate()
WebSecurity Object
C# and VB Syntax
WebSecurity.GetCreateDate(userName)
Parameters
Parameter
Type
Description
userName
String
Return Value
Type
Description
DateTime
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - GetPasswordChangeDate()
WebSecurity Object
Definition
The GetPasswordChangeDate() method returns the date and time a user's password was last
changed.
C# and VB Syntax
WebSecurity.GetPasswordChangedDate(userName)
Parameters
Parameter
Type
Description
userName
String
Return Value
Type
Description
DateTime
Remarks
If the password has never been changed, the GetPasswordChangeDate() 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
WebSecurity - GetUserId()
WebSecurity Object
Definition
The GetUserId() method returns the ID for the specified user.
C# and VB Syntax
WebSecurity.GetUserId(userName)
Parameters
Parameter
Type
Description
userName
String
Return Value
Type
Description
Integer
The user ID
Remarks
The 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
WebSecurity - InitializeDatabaseConnection()
WebSecurity Object
Definition
The InitializeDatabaseConnection() method initializes the WebSecurity database.
The method initializes the WebSecurity system by connecting to the database that contains user and
membership information.
C# and VB Syntax
WebSecurity.InitializeDatabaseConnection(connectionString, userTableName,
userIdColumn, userNameColumn, autoCreateTables)
Parameters
Parameter
Type
Description
connectionString
String
userTableName
String
userIdColumn
String
userNameColumn
String
autoCreateTables
Boolean
Return Value
None.
Remarks
If you are using SQL Server Compact, connectionString should be the name of the WebSecurity
database (without the .sdf file name extension). Otherwise it should be the name of a connection string
in the web configuration (web.config file).
Even if autoCreateTables can force the database tables to be created automatically, the
database itself must always exist.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - IsConfirmed()
WebSecurity Object
Definition
The IsConfirmed() method returns a value that indicates whether the specified user has been
confirmed.
C# and VB Syntax
WebSecurity.IsConfirmed(userName);
Parameters
Parameter
Type
Description
userName
String
Return Value
Type
Description
Boolean
Remarks
The 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
WebSecurity - Login()
WebSecurity Object
Definition
The 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
password
String
persistCookie
String
Return Value
Type
Description
Boolean
Remarks
When 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 logged in. If persistCookie is false, the token is valid
only until the user closes the browser.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - Logout()
WebSecurity Object
Definition
The Logout() method logs out the current user.
C# and VB Syntax
Logout()
Examples
Example C#
// Log out the current user
WebSecurity.Logout();
// Redirect back to the homepage
Response.Redirect("~/");
Example VB
' Log out the current user
WebSecurity.Logout()
' Redirect back to the homepage
Response.Redirect("~/")
Parameters
None.
Return Value
None.
Remarks
When 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 logged
in.
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
WebSecurity - RequireAuthenticatedUser()
WebSecurity Object
Definition
The RequireAuthenticatedUser() method sets the HTTP status to 401 (Unauthorized) if the current
user is not authenticated.
C# and VB Syntax
WebSecurity.RequireAuthenticatedUser()
Parameters
None.
Return Value
None.
Remarks
RequireAuthenticatedUser() only validates if the current user is authenticated. If the current user is
not 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
WebSecurity - RequireRoles()
WebSecurity Object
Definition
The RequireRoles() method sets the HTTP status to 401 (Unauthorized) if the current user is not in
all 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
Return Value
None.
Remarks
RequireRoles() validates that the current user is a member of all of the specified roles. If the user is
not 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
WebSecurity - RequireUser()
WebSecurity Object
Definition
The RequireUser() method sets the HTTP status to 401 (Unauthorized) if the specified user is not
logged on.
C# and VB Syntax
WebSecurity.RequireUser(userId)
or
WebSecurity.RequireUser(userName)
Parameters
Parameter
Type
Description
userID
Integer
The user ID
userName
String
Return Value
None.
Remarks
RequireUser() 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 restrict
access to a page is to create a role, and use the RequireRoles() method to verify that the user is a
member of that role.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - ResetPassword()
WebSecurity Object
Definition
The ResetPassword() method resets a user password using a password token.
C# and VB Syntax
WebSecurity.ResetPassword(passwordResetToken,newPassword)
Parameters
Parameter
Type
Description
passwordResetToken
String
newpassword
String
Return Value
Type
Description
Boolean
Remarks
Use 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 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="New
password" />
<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
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
WebSecurity - UserExists()
WebSecurity Object
Definition
The UserExists() method indicates if the user exists in the WebSecurity database.
C# and VB Syntax
WebSecurity.UserExists(userName)
Parameters
Parameter
Type
Description
userName
String
Return Value
Type
Description
Boolean
Remarks
The 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, or
logged in.
Technical Data
Name
Value
Namespace
WebMatrix.WebData
Assembly
WebMatrix.WebData.dll
WebSecurity Object
Created by www.ebooktutorials.blogspot.in
Next Chapter
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 executes
the 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, like
accessing 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 to
learn.
Razor Syntax
Razor 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 Helpers
ASP.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 Grid
Web Graphics
Google Analytics
Facebook Integration
Twitter Integration
Sending Email
Validation
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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
Example
<!-- Single statement block -->
@Code dim myMessage = "Hello World" End Code
Created by www.ebooktutorials.blogspot.in
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
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
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
</form>
<p>@totalMessage</p>
</body>
</html>
Run example
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Variables
Variables 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 variables
store 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 types
automatically.
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 Types
Below is a list of common data types:
Type
Description
Examples
int
float
Floating-point number
3.14,3.4e38
decimal
1037.196543
bool
Boolean
true, false
string
String
Operators
An operator tells ASP.NET what kind of command to perform in an expression.
The C# language supports many operators. Below is a list ofcommon operators:
Operator
Description
Example
i=6
+
*
/
i=5+5
i=5-5
i=5*5
i=5/5
+=
-=
Increments a variable.
Decrements a variable.
i += 1
i -= 1
==
if (i==10)
!=
if (i!=10)
<
>
<=
>=
Less than.
Greater than.
Less than or equal.
Greater than or equal.
if
if
if
if
(i<10)
(i>10)
(i<=10)
(i>=10)
"w3" + "schools"
DateTime.Hour
()
(i+5)
()
x=Add(i,5)
[]
name[3]
if (!ready)
&&
||
Logical AND.
Logical OR.
Created by www.ebooktutorials.blogspot.in
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 can
be used in calculations.
Below is a list ofcommon conversion methods:
Method
Description
Example
AsInt()
IsInt()
if (myString.IsInt())
{myInt=myString.AsInt();}
AsFloat()
IsFloat()
if (myString.IsFloat())
{myFloat=myString.AsFloat();}
AsDecimal()
IsDecimal()
if (myString.IsDecimal())
{myDec=myString.AsDecimal();}
AsDateTime()
IsDateTime()
myString="10/10/2012";
myDate=myString.AsDateTime();
AsBool()
IsBool()
myString="True";
myBool=myString.AsBool();
ToString()
myInt=1234;
myString=myInt.ToString();
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
For Loops
If 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
Example
<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
</body>
</html>
Run example
While Loops
The 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
Arrays
An 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
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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The If Condition
C# 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 your
test:
The if statement starts a code block
The condition is written inside parenthesis
The 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
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".
Example
@{var price=25;}
<html>
<body>
@if (price>=30)
{
<p>The price is
}
else if (price>20
{
<p>The price is
}
else
{
<p>The price is
}
</body>
</html>
high.</p>
&& price<30)
OK.</p>
low.</p>
Run example
Created by www.ebooktutorials.blogspot.in
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 Conditions
A 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 a
colon, and any number of code lines ending with a break statement. If the test value matches the case
value, the code lines are executed.
A switch block can have a default case (default:) for "everything else" that runs if none of the cases
are true.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Variables
Variables 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 variables store number values (103), date variables store
date 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 Types
Below is a list of common data types:
Type
Description
Examples
integer
double
3.14,3.4e38
decimal
1037.196543
boolean
Boolean
true, false
string
String
Operators
An 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
i=6
+
*
/
i=5+5
i=5-5
i=5*5
i=5/5
+=
-=
Increments a variable.
Decrements a variable.
i += 1
i -= 1
if i=10
<>
if <>10
<
>
<=
>=
Less than.
Greater than.
Less than or equal.
Greater than or equal.
if
if
if
if
&
DateTime.Hour
()
(i+5)
()
x=Add(i,5)
()
name(3)
Not
if Not ready
And
OR
Logical AND.
Logical OR.
AndAlso
orElse
i<10
i>10
i<=10
i>=10
Created by www.ebooktutorials.blogspot.in
Decryptions
Example
AsInt()
IsInt()
if myString.IsInt() then
myInt=myString.AsInt()
end if
AsFloat()
IsFloat()
if myString.IsFloat() then
myFloat=myString.AsFloat()
end if
AsDecimal()
IsDecimal()
if myString.IsDecimal() then
myDec=myString.AsDecimal()
end if
AsDateTime()
IsDateTime()
myString="10/10/2012"
myDate=myString.AsDateTime()
AsBool()
IsBool()
myString="True"
myBool=myString.AsBool()
ToString()
myInt=1234
myString=myInt.ToString()
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
For Loops
If 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
Example
<html>
<body>
<ul>
@For Each x In Request.ServerVariables
@<li>@x</li>
Next x
</ul>
</body>
</html>
Run example
While Loops
The 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>
@Code
Dim i=0
Do While i<5
i += 1
@<p>Line #@i</p>
Loop
End Code
</body>
</html>
Run example
Arrays
An array is useful when you want to store similar variables but don't want to create a separate variable for each of them:
Example
@Code
Dim members As String()={"Jani","Hege","Kai","Jim"}
Created by www.ebooktutorials.blogspot.in
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The If Condition
VB 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 your
test:
The if statement starts a code block
The condition is written between if and then
The code between if ... then and end if is executed if the test is true
Example
@Code
Dim price=50
End Code
<html>
<body>
@If price>30 Then
@<p>The price is too high.</p>
End If
</body>
</html>
Run example
Example
@Code
Dim price=20
End 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".
Example
@Code
Dim price=25
End 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
Created by www.ebooktutorials.blogspot.in
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 Conditions
A select block can be used to test a number of individual conditions:
Example
@Code
Dim weekday=DateTime.Now.DayOfWeek
Dim day=weekday.ToString()
Dim message=""
End Code
<html>
<body>
@Select Case day
Case "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 " & day
End 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, and
any 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 other
cases are true.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
ASP.NET is a development framework for building web pages and
web 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 Model
MVC 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 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 a
time. For example, you can focus on the view without depending on the business logic. It also makes it
easier to test an application.
The MVC separation also simplifies group development. Different developers can work on the view, the
controller logic, and the business logic in parallel.
Created by www.ebooktutorials.blogspot.in
MVC and Web Forms
Drag-and-drop web controls and web components
A 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 one
more time, to install fixes and service packs.
Just click on the link once more.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
Visual 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 programming
language, and the newest Razor server code markup.
Along the way we will explain the content, the code, and all the components of the application.
Created by www.ebooktutorials.blogspot.in
We will explore the content of the files and folders in the next chapter of this tutorial.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
MVC Folders
A typical ASP.NET MVC web application has the following folder content:
Application information
Properties
References
Application folders
App_Data Folder
Content Folder
Controllers Folder
Models Folder
Scripts Folder
Views Folder
Configuration files
Global.asax
packages.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 the
Views 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:
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.
Created by www.ebooktutorials.blogspot.in
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 edit the layout files in the next chapter of this tutorial.
Created by www.ebooktutorials.blogspot.in
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Adding a Layout
The 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 Helpers
In 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 Syntax
In 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 Styles
The 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
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;
}
@{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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}
public ActionResult About()
{return View();}
}
}
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Extention
Plain HTML
.htm or .html
Classic ASP
.asp
Classic ASP.NET
.aspx
ASP.NET Razor C#
.cshtml
ASP.NET Razor VB
.vbhtml
Created by www.ebooktutorials.blogspot.in
Click on the "Home" tab and the "About" tab to see how it works.
Congratulations
Congratulations. 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 next
chapters of this tutorial.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Type
Allow Nulls
ID
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
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 looks
strange, but this is the naming convention you have to use to make the controller connect to the database table.
Title
Director
Date
Psycho
Alfred Hitchcock
01.01.1960
La Dolce Vita
Federico Fellini
01.01.1960
Note: The ID column is updated automatically. You should not edit it.
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
MVC Models
The 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.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
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.
Congratulations
Content Downloaded from www.w3schools.com
Created by www.ebooktutorials.blogspot.in
Congratulations. You have added your first MVC data model to your application.
Now you can click on the "Movies" tab :-)
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Created by www.ebooktutorials.blogspot.in
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
HTML Helpers
With 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 HTML
helper 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.
HTML Links
The 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:
Description
.linkText
.actionName
.routeValues
.controllerName
.htmlAttributes
.protocol
.hostname
.fragment
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#:
Created by www.ebooktutorials.blogspot.in
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
ASP.NET Syntax C#:
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Learn how to publish an MVC application without using Visual Web Developer.
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>
Created by www.ebooktutorials.blogspot.in
THAT'S IT. GOOD LUCK !
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Classes
Class
Description
AcceptVerbsAttribute
ActionDescriptor
ActionExecutedContext
ActionExecutingContext
ActionFilterAttribute
ActionMethodSelectorAttribute
ActionNameAttribute
ActionNameSelectorAttribute
ActionResult
AdditionalMetadataAttribute
AjaxHelper
AjaxHelper(Of TModel)
AjaxRequestExtensions
AllowHtmlAttribute
AreaRegistration
AreaRegistrationContext
AssociatedMetadataProvider
AssociatedValidatorProvider
AsyncController
AsyncTimeoutAttribute
AuthorizationContext
AuthorizeAttribute
BindAttribute
BuildManagerCompiledView
Represents the base class for views that are compiled by the
BuildManager class before being rendered by a view engine.
BuildManagerViewEngine
ByteArrayModelBinder
ChildActionOnlyAttribute
ChildActionValueProvider
ChildActionValueProviderFactory
ClientDataTypeModelValidatorProvider
CompareAttribute
ContentResult
Controller
ControllerActionInvoker
Created by www.ebooktutorials.blogspot.in
methods of a controller.
ControllerBase
ControllerBuilder
ControllerContext
ControllerDescriptor
ControllerInstanceFilterProvider
CustomModelBinderAttribute
DataAnnotationsModelMetadata
DataAnnotationsModelValidator(Of
TAttribute)
DefaultControllerFactory
DefaultModelBinder
DefaultViewLocationCache
DependencyResolver
DependencyResolverExtensions
DictionaryValueProvider(Of TValue)
EmptyModelMetadataProvider
EmptyModelValidatorProvider
EmptyResult
ExceptionContext
ExpressionHelper
FieldValidationMetadata
FileContentResult
FilePathResult
FileResult
FileStreamResult
Filter
FilterAttribute
FilterAttributeFilterProvider
FilterInfo
FilterProviderCollection
FilterProviders
FormCollection
FormContext
FormValueProvider
FormValueProviderFactory
GlobalFilterCollection
GlobalFilters
HandleErrorAttribute
Created by www.ebooktutorials.blogspot.in
HandleErrorInfo
HiddenInputAttribute
HtmlHelper
HtmlHelper(Of TModel)
HttpDeleteAttribute
HttpFileCollectionValueProvider
HttpFileCollectionValueProviderFactory
HttpGetAttribute
HttpNotFoundResult
HttpPostAttribute
HttpPostedFileBaseModelBinder
HttpPutAttribute
HttpRequestExtensions
HttpStatusCodeResult
HttpUnauthorizedResult
JavaScriptResult
JsonResult
JsonValueProviderFactory
LinqBinaryModelBinder
ModelBinderAttribute
ModelBinderDictionary
ModelBinderProviderCollection
ModelBinderProviders
ModelBinders
ModelBindingContext
ModelClientValidationEqualToRule
ModelClientValidationRangeRule
ModelClientValidationRegexRule
ModelClientValidationRemoteRule
ModelClientValidationRequiredRule
ModelClientValidationRule
ModelClientValidationStringLengthRule
ModelError
ModelErrorCollection
ModelMetadata
ModelMetadataProvider
ModelMetadataProviders
ModelState
ModelStateDictionary
ModelValidationResult
Created by www.ebooktutorials.blogspot.in
ModelValidator
ModelValidatorProvider
ModelValidatorProviderCollection
ModelValidatorProviders
MultiSelectList
MvcFilter
MvcHandler
MvcHtmlString
MvcHttpHandler
MvcRouteHandler
MvcWebRazorHostFactory
NameValueCollectionExtensions
NameValueCollectionValueProvider
NoAsyncTimeoutAttribute
NonActionAttribute
OutputCacheAttribute
ParameterBindingInfo
ParameterDescriptor
PartialViewResult
PreApplicationStartCode
QueryStringValueProvider
QueryStringValueProviderFactory
RangeAttributeAdapter
RazorView
RazorViewEngine
RedirectResult
RedirectToRouteResult
ReflectedActionDescriptor
ReflectedControllerDescriptor
ReflectedParameterDescriptor
RegularExpressionAttributeAdapter
RemoteAttribute
RequiredAttributeAdapter
RequireHttpsAttribute
ResultExecutedContext
ResultExecutingContext
RouteCollectionExtensions
RouteDataValueProvider
RouteDataValueProviderFactory
SelectList
SelectListItem
Created by www.ebooktutorials.blogspot.in
class.
SessionStateAttribute
SessionStateTempDataProvider
StringLengthAttributeAdapter
TempDataDictionary
TemplateInfo
UrlHelper
UrlParameter
ValidatableObjectAdapter
ValidateAntiForgeryTokenAttribute
ValidateInputAttribute
ValueProviderCollection
ValueProviderDictionary
ValueProviderFactories
ValueProviderFactory
ValueProviderFactoryCollection
ValueProviderResult
ViewContext
ViewDataDictionary
ViewDataDictionary(Of TModel)
ViewDataInfo
ViewEngineCollection
ViewEngineResult
ViewEngines
ViewMasterPage
ViewMasterPage(Of TModel)
ViewPage
ViewPage(Of TModel)
ViewResult
ViewResultBase
ViewStartPage
ViewTemplateUserControl
ViewTemplateUserControl(Of TModel)
ViewType
ViewUserControl
ViewUserControl(Of TModel)
VirtualPathProviderViewEngine
WebFormView
WebFormViewEngine
WebViewPage
WebViewPage(Of TModel)
Created by www.ebooktutorials.blogspot.in
Interfaces
Interface
Description
IActionFilter
IActionInvoker
IAuthorizationFilter
IClientValidatable
IController
IControllerActivator
IControllerFactory
IDependencyResolver
IExceptionFilter
IFilterProvider
IMetadataAware
IModelBinder
IModelBinderProvider
IMvcFilter
Defines members that specify the order of filters and whether multiple
filters are allowed.
IResultFilter
IRouteWithArea
ITempDataProvider
Defines the contract for temporary-data providers that store data that is
viewed on the next request.
Defines the methods that are required for a value provider in ASP.NET
MVC.
IView
IViewDataContainer
Defines the methods that are required for a view data dictionary.
IViewEngine
IViewLocationCache
Defines the methods that are required in order to cache view locations in
memory.
IViewPageActivator
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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.
Created by www.ebooktutorials.blogspot.in
Visual Web Developer supports two different development types:
Web Projects
Web Sites
Web Sites
A 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.
Name the Web Site DemoWF and set the disk (File System) location to something like c:\w3schools_demo\DemoWF before clicking OK.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Create
Create
Create
Create
Create
2. Create Folders
In the folder named "DemoWF" (your website), create 5 folders:
Account - for storing login and membership files
App_Data - for storing databases and data files
Images - for storing images
Scripts - for storing browser scripts
Styles - for storing css styles
To create a new folder, right-click the root folder and select "New Folder..."
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
}
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"
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>© <%=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).
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.
Congratulations
You 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.
Description
.htm / .html
HTML Pages
Web pages to be viewed directly by the browser
Created by www.ebooktutorials.blogspot.in
.css
Style Sheets
Defines styles and formatting for the web site
.js
JavaScripts
Contains JavaScripts to be executed in the browser
.aspx
Web Forms
The core of ASP.NET. Web pages with ASP.NET code.
.ascx
.asax
Global Class
Global code (like startup code)
.asmx
Web Service
Contains callable web services
.cs
Class Files
Contains code in C#
.vb
Class Files
Contains code in Vb (Visual Badsic)
.config
Web Configuration
Contains configuration information for the web site
.master
Master Pages
Define the global structure (look) of the web site
.sitemap
XML Sitemap
.xml
.sdf
.mdf
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Add an about page
Add a navigation menu
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.
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>© <%=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 unordered
list (marked red).
Site.css
body
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
color: #ffffff;
}
Created by www.ebooktutorials.blogspot.in
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 an
unordered list (marked red).
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
Congratulations
You have added navigation to your website.
In the next chapter we will add a database.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
What We Will Do
In this chapter we will:
Create a database
Add data to the database
Create a page to list the database
Type
Allow Nulls
ID
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
When you have finished creating the table columns, save the table and name it Movies.
Title
Director
Date
Psycho
Alfred Hitchcock
01.01.1960
La Dolce Vita
Federico Fellini
01.01.1960
Note: The ID column is updated automatically. You should not edit it.
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
<asp:BoundField
<asp:BoundField
<asp:BoundField
</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
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>
Congratulations
You have added a database to your web project.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
ASP.NET is a development framework for building web pages and
web 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.
ASP.NET References
At the end of this tutorial you will find a complete ASP.NET reference with objects, components, properties and methods.
ASP.NET Reference
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Hello W3Schools
To 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!
<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
<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
Classic ASP
Active 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.
<html>
<body bgcolor="yellow">
<center>
<h2>Hello W3Schools!</h2>
<p><%Response.Write(now())%></p>
</center>
</body>
</html>
Created by www.ebooktutorials.blogspot.in
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
<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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next 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.
<script runat="server">
Sub Page_Load
link1.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.
<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
Created by www.ebooktutorials.blogspot.in
</script>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
</body>
</html>
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:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
</p>
</form>
</body>
</html>
Show example
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
<%
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..."
Example
<script runat="server">
Sub Page_Load
lbl1.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
Example
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
lbl1.Text="The date and time is " & now()
end if
End 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, the
submit subroutine will write "Hello World!" to the second label, but the date and time in the first label will not change.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
All server controls must appear within a <form> tag, and the <form> tag must contain
the runat="server" attribute.
<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 specify
the 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 id
attribute specified, you will see that ASP.NET has added these attributes to the form. It looks
something like this:
Submitting a Form
A form is most often submitted by clicking on a button. The Button server control in ASP.NET has the
following format:
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
You may save a lot of coding by maintaining the ViewState of the objects in your Web
Form.
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 fname
fname=Request.Form("fname")
If fname<>"" Then
Response.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 NOT
disappear:
Example
Click view source in the right frame of the example to see that ASP .NET has added a hidden field in
the 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The TextBox control is used to create a text box where the user can input text.
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 Script
The 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 button
or 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.Text
End 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 click
outside 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
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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
<html>
<body>
<form runat="server">
<asp:Button id="b1" Text="Submit" runat="server" />
</form>
</body>
</html>
Add a Script
A 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.Text
End 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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 Binding
The following controls are list controls which support data binding:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp: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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Create an ArrayList
The 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_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
end if
end sub
</script>
By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with the
TrimToSize() method:
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
end if
end sub
</script>
An ArrayList can also be sorted alphabetically or numerically with the Sort() method:
<script runat="server">
Sub Page_Load
if 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 if
end sub
</script>
To sort in reverse order, apply the Reverse() method after the Sort() method:
<script runat="server">
Sub Page_Load
if 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 if
end sub
</script>
Created by www.ebooktutorials.blogspot.in
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp: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" />
</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_Load
if 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 if
end 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 data
source of the RadioButtonList control. The DataBind() method of the RadioButtonList control binds the
data source with the RadioButtonList control.
Note: The data values are used as both the Text and Value properties for the control. To add Values
that are different from the Text, use either the Hashtable object or the SortedList object.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Create a Hashtable
The 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 through
their 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_Load
if 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 if
end sub
</script>
Data Binding
A Hashtable object may automatically generate the text and values to the following controls:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp: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_Load
if 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 if
end 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 appear
in a label:
Created by www.ebooktutorials.blogspot.in
Example
<script runat="server">
sub Page_Load
if 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 if
end sub
sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end 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.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
CheckBoxList
DropDownList
RadioButtonList
ListBox
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
Norway
Norway
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
Norway
France
Italy
Sweden
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Next Chapter
The SortedList object combines the features of both the ArrayList object and the Hashtable object.
<script runat="server">
sub Page_Load
if 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 if
end sub
</script>
Data Binding
A SortedList object may automatically generate the text and values to the following controls:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp: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_Load
if 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 if
end 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 appear
in a label:
Example
Created by www.ebooktutorials.blogspot.in
<script runat="server">
sub Page_Load
if 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 if
end sub
sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
France
Italy
Norway
Sweden
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
CheckBoxList
DropDownList
ListBox
RadioButtonList
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub Page_Load
if 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 if
end sub
France
France
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Next Chapter
An XML File
Here is an XML file named "countries.xml":
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
end if
end 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:
Created by www.ebooktutorials.blogspot.in
</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 appear
in a label:
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if 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 if
end sub
sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end 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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The Repeater control is used to display a repeated list of items that are bound to the
control.
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
end if
end sub
Then we create a Repeater control in an .aspx page. The contents of the <HeaderTemplate> element
are rendered first and only once within the output, then the contents of the <ItemTemplate> element
are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element
are rendered once within the output:
<html>
<body>
<form runat="server">
<asp:Repeater id="cdcatalog" runat="server">
<HeaderTemplate>
...
</HeaderTemplate>
Created by www.ebooktutorials.blogspot.in
<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 Repeater
control. We also fill the Repeater control with HTML tags and bind the data items to the cells in
the<ItemTemplate> section with the <%#Container.DataItem("fieldname")%> method:
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end 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
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end sub
</script>
<html>
<body>
<form runat="server">
Created by www.ebooktutorials.blogspot.in
<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
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end 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
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
Show example
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
The 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 a table around the data items by default.
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
end if
end 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 the
contents of the <ItemTemplate> element are repeated for each "record" in the DataSet, and last, the contents of the <FooterTemplate> element are
rendered 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
<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> that
contains 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_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end 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 Styles
You can also add styles to the DataList control to make the output more fancy:
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end 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
</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
Example
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycdcatalog=New DataSet
mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))
cdcatalog.DataSource=mycdcatalog
cdcatalog.DataBind()
end if
end 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>
© Hege Refsnes
</FooterTemplate>
</asp:DataList>
</form>
</body>
</html>
Show example
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
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.
What is ADO.NET?
ADO.NET
ADO.NET
ADO.NET
ADO.NET
Create a DataReader
The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is
created by calling the ExecuteReader method of the OleDbCommand object:
Created by www.ebooktutorials.blogspot.in
Example
<%@ Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=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=dbread
customers.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
dbread.Close()
dbconn.Close()
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
Companyname
Alfreds
Futterkiste
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New
OleDbConnection("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=dbread
customers.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>
Copyright: W3Schools.com
Address
City
Maria Anders
Obere Str. 57
Berglunds
snabbkp
Christina
Berglund
Berguvsvgen
Lule
8
Centro comercial
Moctezuma
Ernst Handel
FISSA Fabrica
Inter. Salchichas
S.A.
Francisco
Sierras de
Mxico
Chang
Granada 9993 D.F.
Roland Mendel Kirchgasse 6 Graz
Berlin
Diego Roel
C/ Moralzarzal,
Madrid
86
Galera del
gastrnomo
Eduardo
Saavedra
Rambla de
Barcelona
Catalua, 23
Island Trading
Helen Bennett
Garden House
Cowes
Crowther Way
Brandenburg
Vancouver
Magazzini
Giovanni
Alimentari Riuniti Rovelli
Via Ludovico il
Bergamo
Moro 22
North/South
Paris
spcialits
Rattlesnake
Canyon Grocery
Simons bistro
<ItemTemplate>
Contactname
South House
London
300
Queensbridge
265, boulevard
Marie Bertrand
Paris
Charonne
Simon
Crowther
Paula Wilson
Jytte Petersen
2817 Milton
Dr.
Vinbltet 34
Albuquerque
Kbenhavn
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
Customers Table
Alfreds Futterkiste in Obere Str. 57, Berlin
Berglunds snabbkp in Berguvsvgen 8, Lule
Centro comercial Moctezuma in Sierras de Granada 9993,
Mxico D.F.
Ernst Handel in Kirchgasse 6, Graz
FISSA Fabrica Inter. Salchichas S.A. in C/ Moralzarzal, 86,
Madrid
Galera del gastrnomo in Rambla de Catalua, 23, Barcelona
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New
OleDbConnection("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=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:DataList
id="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"
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Next Chapter
Master pages provide templates for other pages on your web site.
Master Pages
Master 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 can
be 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 the
content page.
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Dynamic Menu
The <asp:Menu> control displays a standard site navigation menu.
Code Example:
TreeView
The <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:
Created by www.ebooktutorials.blogspot.in
SiteMapPath
The 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 by
default.
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
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Next Chapter
Description
HtmlAnchor
HtmlButton
HtmlForm
HtmlGeneric
HtmlImage
HtmlInputButton
HtmlInputCheckBox
HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlSelect
HtmlTable
HtmlTableCell
HtmlTableRow
HtmlTextArea
Previous
Next Chapter
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Disabled
HRef
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. Special characters are automatically converted to HTML entities
Name
OnServerClick
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Target
Title
A title to be displayed by the browser (like the title attribute of the img
element)
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLAnchor
Declare two HtmlAnchor controls in an .aspx file (remember to embed the control inside an HtmlForm
control). Then modify the URL, target, and title of the HtmlAnchor controls in an event 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 .NET understands.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
id
InnerHtml
Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not
automatically converted to HTML entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML element. Special characters are
automatically converted to HTML entities
OnServerClick
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLButton
Declare two HtmlButton controls in an .aspx file (remember to embed the control inside an HtmlForm control). Next, write an event handler that specifies
what to happen when a button is clicked.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Action
A URL that defines where to send the data when the form is submitted.
Attributes
Disabled
EncType
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. 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
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Target
Visible
A Boolean value that indicates whether or not the control should be visible
Note: This attribute is always set to the URL of the page itself!
Example
HTMLForm
Declare 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 is
triggered, the submit subroutine is executed. The submit subroutine writes a welcome message to the
p element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
id
InnerHtml
Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not
automatically converted to HTML entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML element. Special characters are
automatically converted to HTML entities
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLGeneric
Declare one HtmlInputText controls, one HtmlInputButton control, and one HtmlGeneric control (the <p> tag) in an .aspx file (remember to embed the
controls inside an HtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine writes a welcome
message to the p element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Align
Alt
Attributes
Border
Disabled
Height
id
runat
Src
Style
Sets or returns the CSS properties that are applied to the control
TagName
Visible
A Boolean value that indicates whether or not the control should be visible
Width
Examples
HTMLImage
Declare an HtmlImage control in an .aspx file (remember to embed the control inside an HtmlForm
control). Then we modify the src, alt and border properties of the HtmlImage control in an event
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 .NET understands:
HTMLImage 2
Declare an HtmlImage and an HTMLSelect control in an .aspx file (remember to embed the controls
inside an HtmlForm control). Then we modify the src property of the HtmlImage control based on user
choices. The value selected in the HtmlSelect control determines which image to display.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
id
Name
OnServerClick
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLInputbutton
Declare 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 is triggered, the submit subroutine is executed. The submit subroutine writes a welcome message to the p
element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Description
Attributes
Checked
Disabled
id
Name
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Event
Description
ServerChange
Example
HTMLInputCheckbox
Declare 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 is
triggered, 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
Properties
Property
Description
Accept
Attributes
Disabled
id
MaxLength
Name
PostedFile
runat
Size
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
Declare 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 is
triggered, 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>
Created by www.ebooktutorials.blogspot.in
Description
Attributes
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
id
Name
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Event
Description
ServerChange
Example
HTMLInputHidden
Declare one HtmlInputHidden control, one HtmlInputText control, one HtmlInputButton control, and one HtmlGeneric control in an .aspx file (remember to
embed the controls inside an HtmlForm control). When the submit button is triggered, the submit subroutine is executed. The submit subroutine sets the
value 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
Description
Align
Alt
Attributes
Border
Disabled
id
Name
OnServerClick
runat
Src
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLInputImage
Declare two HtmlInputImage controls and one HtmlGeneric control in an .aspx file (remember to embed
the controls inside an HtmlForm control). If the user clicks on the first image, the button1 subroutine is
executed. This subroutine sends the message "You clicked the smiley button!" to the p element. If the
user clicks on the second image, the button2 subroutine is executed. This subroutine sends the
message "You clicked the angry button!" to the p element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Checked
Disabled
id
Name
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLInputRadiobutton
Declare three HtmlInputRadioButton 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 is triggered, the submit subroutine is executed. The submit subroutine may respond in three
ways: if the radiobutton with id="r1" is selected, the server sends the message "Your favorite color is
red" to the p element. If the radiobutton with id="r2" is selected, the server sends the message "Your
favorite color is green" to the p element. If the radiobutton with id="r3" is selected, the server sends
the message "Your favorite color is blue" to the p element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
id
MaxLength
Name
runat
Size
Style
Sets or returns the CSS properties that are applied to the control
TagName
Type
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLInputText
Declare 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 is triggered, the submit subroutine is executed. The submit subroutine writes a welcome message to the p
element.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Attributes
DataMember
DataSource
DataTextField
DataValueField
A field in the data source that specifies the value of each selectable item in
the drop-down list
Disabled
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. Special characters are automatically converted to HTML entities
Items
Multiple
OnServerChange
The name of the function to be executed when the selected item has
changed
runat
SelectedIndex
Size
Style
Sets or returns the CSS properties that are applied to the control
TagName
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLSelect
Declare an HtmlImage and an HTMLSelect control in an .aspx file (remember to embed the controls
inside an HtmlForm control). Then modify the src property of the HtmlImage control based on user
choices. The value selected in the HtmlSelect control determines which image to display.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Align
Attributes
BGColor
Border
BorderColor
CellPadding
CellSpacing
Disabled
Height
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. Special characters are automatically converted to HTML entities
Rows
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Visible
A Boolean value that indicates whether or not the control should be visible
Width
Examples
HTMLTable
Declare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspx
file (remember to embed the controls inside an HtmlForm control). The user may choose number of
cells and rows. When the submit button is triggered, the submit subroutine is executed. The submit
subroutine generates the table based on what the user did input.
HTMLTable 2
Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed the
controls inside an HtmlForm control). When the submit button is triggered, the submit subroutine is
executed. The submit subroutine modifies the background color and the border color of the table, it
also changes the contents of the cells.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Align
Attributes
BGColor
BorderColor
ColSpan
Disabled
Height
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. Special characters are automatically converted to HTML entities
Nowrap
A Boolean value that specifies whether or not the text within this control
should wrap
RowSpan
runat
Style
TagName
VAlign
Visible
A Boolean value that indicates whether or not the control should be visible
Width
Examples
HTMLTable
Declare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspx
file (remember to embed the controls inside an HtmlForm control). The user may choose number of
cells and rows. When the submit button is triggered, the submit subroutine is executed. The submit
subroutine generates the table based on what the user did input.
HTMLTable 2
Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed the
controls inside an HtmlForm control). When the submit button is triggered, the submit subroutine is
executed. The submit subroutine modifies the background color and the border color of the table, it
also changes the contents of the cells.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
Align
Attributes
BGColor
BorderColor
Cells
Disabled
A Boolean value that indicates whether or not the control should be disabled. Default is false
Height
id
InnerHtml
Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not
automatically converted to HTML entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML element. Special characters are
automatically converted to HTML entities
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
VAlign
Visible
A Boolean value that indicates whether or not the control should be visible
Examples
HTMLTable
Declare two HtmlSelect controls, one HtmlInputButton control, and one HtmlTable control in an .aspx file (remember to embed the controls inside an
HtmlForm control). The user may choose number of cells and rows. When the submit button is triggered, the submit subroutine is executed. The submit
subroutine generates the table based on what the user did input.
HTMLTable 2
Declare an HtmlTable control and an HtmlInputButton control in an .aspx file (remember to embed the controls inside an HtmlForm control). When the
submit button is triggered, the submit subroutine is executed. The submit subroutine modifies the background color and the border color of the table, it also
changes the contents of the cells.
HTML Server Controls
Created by www.ebooktutorials.blogspot.in
Description
Attributes
Cols
Disabled
id
InnerHtml
Sets or returns the content between the opening and closing tags of the
HTML element. Special characters are not automatically converted to HTML
entities
InnerText
Sets or returns all text between the opening and closing tags of the HTML
element. Special characters are automatically converted to HTML entities
Name
OnServerChange
The name of the function to be executed when the contents of the textarea
is changed
Rows
runat
Style
Sets or returns the CSS properties that are applied to the control
TagName
Value
Visible
A Boolean value that indicates whether or not the control should be visible
Example
HTMLTextarea
Declare an HtmlTextarea control, an HtmlInputButton control, and an HtmlGeneric control in an .aspx
file (remember to embed the controls inside an HtmlForm control). When the submit button is
triggered, 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
Description
<ImageUrl>
<NavigateUrl>
<AlternateText>
<Keyword>
<Impressions>
Properties
Property
Description
.NET
AdvertisementFile
1.0
AlternateTextField
2.0
ImageUrlField
2.0
KeywordFilter
1.0
NavigateUrlField
2.0
runat
1.0
Target
1.0
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
CausesValidation
1.0
CommandArgument
1.0
CommandName
1.0
OnClientClick
2.0
PostBackUrl
Specifies the URL of the page to post to from the current page when 2.0
a button is clicked
runat
Specifies that the control is a server control. Must be set to "server" 1.0
Text
1.0
UseSubmitBehavior
2.0
ValidationGroup
2.0
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>
Click me!
<!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
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>
Click me!
<!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
Properties
Property
Description
.NET
Caption
2.0
CaptionAlign
2.0
CellPadding
1.0
CellSpacing
1.0
DayHeaderStyle
1.0
DayNameFormat
1.0
DayStyle
1.0
FirstDayOfWeek
1.0
NextMonthText
1.0
NextPrevFormat
1.0
NextPrevStyle
1.0
OtherMonthDayStyle
The style for displaying days that are not in the current month
1.0
PrevMonthText
1.0
runat
1.0
SelectedDate
1.0
SelectedDates
1.0
SelectedDayStyle
1.0
SelectionMode
1.0
SelectMonthText
1.0
SelectorStyle
1.0
SelectWeekText
1.0
ShowDayHeader
1.0
ShowGridLines
1.0
ShowNextPrevMonth
1.0
ShowTitle
1.0
TitleFormat
1.0
TitleStyle
1.0
TodayDayStyle
1.0
TodaysDate
Today's date
1.0
UseAccessibleHeader
2.0
VisibleDate
The date that specifies the month that is currently visible in the 1.0
calendar
WeekendDayStyle
1.0
OnDayRender
OnSelectionChanged
OnVisibleMonthChanged
Created by www.ebooktutorials.blogspot.in
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
<
Sun
24
1
8
15
22
29
<form runat="server">
<asp:Calendar runat="server" />
</form>
</body>
</html>
Copyright: W3Schools.com
Mon
25
2
9
16
23
30
July 2012
Tue Wed Thu
26 27 28
3
4
5
10 11 12
17 18 19
24 25 26
31
1
2
>
Fri Sat
29 30
6
7
13 14
20 21
27 28
3
4
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
<
July 2012
>
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
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
<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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
<
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
<form runat="server">
<asp:Calendar DayNameFormat="Full" runat="server"
SelectionMode="DayWeekMonth"
SelectMonthText="<*>"
SelectWeekText="<->"/>
<SelectorStyle BackColor="#f5f5f5" />
</asp:Calendar>
</form>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar Caption="text" runat="server" />
Attribute
Description
text
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar Caption="text" CaptionAlign="align" runat="server" />
Attribute
Description
align
Example
The following example sets the Caption property in a calendar and aligns it to the bottom of the
calendar:
<form runat="server">
<asp:Calendar id="cal1" runat="server"
Caption="This is a Caption text"
CaptionAlign="bottom" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar CellPadding="pixels" runat="server" />
Attribute
Description
pixels
Specifies the space (in pixels) between the border and the contents of a calendar
cell
Example
The following example shows a calendar with CellPadding 15:
<form runat="server">
<asp:Calendar id="cal1" runat="server" CellPadding="15" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar CellSpacing="pixels" runat="server" />
Attribute
Description
pixels
Example
The following example shows a calendar with CellSpacing 15:
<form runat="server">
<asp:Calendar id="cal1" runat="server" CellSpacing="15" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The following example shows another way to set the DayHeaderStyle in a calendar:
Try-It-Yourself Demos
Set DayHeaderStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar DayNameFormat="format" runat="server" />
Attribute
Description
format
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
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set DayStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar FirstDayOfWeek="day" runat="server" />
Attribute
Description
day
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar NextMonthText="string" runat="server" />
Attribute
Description
string
Specifies the text displayed for the next month link in the calendar. The default
value 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
Created by www.ebooktutorials.blogspot.in
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:
ShortMonth
FullMonth
CustomText
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
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set NextPrevStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set OtherMonthDayStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar PrevMonthText="string" runat="server" />
Attribute
Description
string
Specifies the text displayed for the previous month link in the calendar. The
default 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
Created by www.ebooktutorials.blogspot.in
Example
The following example outputs the selected date when a date is selected:
Created by www.ebooktutorials.blogspot.in
Example
The following example outputs the selected dates when a date is selected:
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set SelectedDayStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar SelectionMode="mode" runat="server" />
Attribute
Description
mode
Example
The following example sets the SelectionMode of a calendar:
<form runat="server">
<asp:Calendar id="cal1" runat="server"
SelectionMode="DayWeekMonth" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar SelectMonthText="string" runat="server" />
Attribute
Description
string
Specifies the text displayed for selecting an entire month in a calendar. The
default 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
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set SelectorStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Calendar TitleFormat="mode" runat="server" />
Attribute
Description
mode
Example
The following example sets the TitleFormat to display month:
<form runat="server">
<asp:Calendar id="cal1" runat="server"
TitleFormat="Month" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set TitleStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
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 and
their values
value
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 2
The 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 Demos
Set TodayDayStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Example
The following example shows a outputs today's date:
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
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 2
The 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 Demos
Set WeekendDayStyle of a Calendar control (with declaration and script)
Complete Calendar Control Reference
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
Date
1.0
DayNumberText
1.0
IsOtherMonth
Specifies if the date in another month than the one displayed in 1.0
the calendar
IsSelectable
1.0
IsSelected
1.0
IsToday
1.0
IsWeekend
1.0
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
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 If
End Sub
</script>
<form runat="server">
<form runat="server">
The weekends are not selectable
<asp:Calendar id="cal1" runat="server"
OnDayRender="DaySelect" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
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 If
End 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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
SelectedIndex
1.0
OnSelectedIndexChanged
1.0
runat
1.0
Example
DropdownList
Declare one DropDownList control in an .aspx file. Then create an event handler for the Click event
which displays some text and the selected item, in a Label control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
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.Text
End 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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
mess.Text="You selected " & drop1.SelectedItem.Text
End Sub
</script>
Item11
Item
<!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>
Copyright: W3Schools.com
Submit
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
ImageUrl
1.0
NavigateUrl
1.0
runat
1.0
Target
1.0
Text
1.0
Example
Hyperlink
Declare a HyperLink control in an .aspx file.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:HyperLink ImageUrl="URL" runat="server" />
Attribute
Description
URL
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:HyperLink NavigateUrl="URL" runat="server" />
Attribute
Description
URL
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:HyperLink Target="target" runat="server" />
Attribute
Description
target
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:HyperLink Text="string" runat="server" />
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:HyperLink
ImageUrl="/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
WEB HOSTING
Cloud Hosting
Properties
Property
Description
.NET
AlternateText
1.0
DescriptionUrl
2.0
GenerateEmptyAlternateText
2.0
ImageAlign
1.0
ImageUrl
1.0
runat
Specifies that the control is a server control. Must be set to "server" 1.0
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 Statistics
Browser OS
Browser Display
SHARE THIS PAGE
Share with
Example
Image
Declare an Image control in an .aspx file.
Web Server Controls
REPORT
ERROR
HOME
TOP
FORUM
ABOUT
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Image AlternateText="text" runat="server" />
Attribute
Description
text
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Image ImageAlign="align" runat="server" />
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Image ImageUrl="URL" runat="server" />
Attribute
Description
URL
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:Image
runat="server"
AlternateText="W3Schools"
ImageUrl="/banners/w6.gif"/>
</form>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
CausesValidation
1.0
CommandArgument
1.0
CommandName
1.0
GenerateEmptyAlternateText
2.0
OnClientClick
2.0
PostBackUrl
The URL of the page to post to from the current page when the 2.0
ImageButton control is clicked
runat
1.0
TagKey
1.0
ValidationGroup
The group of controls for which the ImageButton control causes 2.0
validation when it posts back to the server
Note: The properties of the Image control can also be used on the ImageButton control.
Example
ImageButton
Declare one ImageButton control and one Label control in an .aspx file. When the user clicks on the
image, 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
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ImageButton OnClientClick="func" runat="server" />
Attribute
Description
func
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
Created by www.ebooktutorials.blogspot.in
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, this
causes 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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ImageButton ValidationGroup="group" runat="server" />
Attribute
Description
group
Example
The following example validates the specific validation group:
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub getCoordinates(sender As Object, e As ImageClickEventArgs)
mess.Text="Coordinates: " & e.x & ", " & e.y
End Sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<p>Click on the image:</p>
<asp:ImageButton
runat="server"
ImageUrl="smiley.gif"
OnClick="getCoordinates"/>
<p><asp:label id="mess" runat="server"/></p>
</form>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
runat
Text
Example
Label
Declare one Label control, one TextBox control, and one Button control in an .aspx file. When the user
clicks on the button, the submit subroutine is executed. The subroutine copies the content of the
TextBox control to the Label control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub submit(Sender As Object, e As EventArgs)
label1.Text=txt1.Text
End 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>
Copyright: W3Schools.com
Copy to Label
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
CausesValidation
1.0
CommandArgument
1.0
CommandName
1.0
OnClientClick
2.0
PostBackUrl
The URL of the page to post to from the current page when the LinkButton control is clicked
2.0
runat
1.0
Text
1.0
ValidationGroup
The group of controls for which the LinkButton control causes validation when it posts back to the 2.0
server
Example
LinkButton
Declare one LinkButton control and one Label control in an .aspx file. When the user clicks on the link, the lbClick subroutine is executed. The subroutine
sends the text "You clicked the LinkButton control" to the Label control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:LinkButton OnClientClick="func" runat="server" />
Attribute
Description
func
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
Created by www.ebooktutorials.blogspot.in
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, this
causes 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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:LinkButton Text="string" runat="server" />
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:LinkButton ValidationGroup="group" runat="server" />
Attribute
Description
group
Example
The following example validates the specific validation group:
Created by www.ebooktutorials.blogspot.in
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>
Click me!
<!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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
Rows
1.0
SelectionMode
1.0
Example
Listbox
Declare 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 Label
control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ListBox Rows="num" runat="server">
Some Content
</asp:ListBox>
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ListBox SelectionMode="mode" runat="server">
Some Content
</asp:ListBox>
Attribute
Description
mode
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub submit(Sender As Object,e As EventArgs)
mess.Text="You selected " & drop1.SelectedItem.Text
End Sub
</script>
Item
Item11
Item 2
Item 2
Item 3
Item43
Item
Item54
Item
<!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>
Copyright: W3Schools.com
Submit
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ListItem
Enabled="True|False"
Selected="True|False"
Text="label"
Value="value" />
Properties
Property
Description
.NET
Attributes
1.0
Enabled
2.0
Selected
1.0
Text
1.0
Value
1.0
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 below
shows 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
Examples
Content Downloaded from www.w3schools.com
Created by www.ebooktutorials.blogspot.in
Basic ListItem in BulletedList
A BulletedList control with two ListItems in an .aspx file.
ListItems with different properties in ListBox
A ListBox control with some ListItems in an .aspx file. The items in the list uses different properties to
show the ListItem text.
ListItem disabled in ListBox
A ListBox control with one of the ListItems disabled.
ListItem selected in RadioButtonList
A RadioButtonList control with one of the ListItems selected.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ListItem Text="string" runat="server" />
Attribute
Description
string
It is possible to use the Text or Value properties and the inner HTML text to set the text displayed for
an 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 below
shows 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
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:ListItem Value="string" runat="server" />
Attribute
Description
string
It is possible to use the Text or Value properties and the inner HTML text to set the text displayed for
an 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 below
shows 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
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
Item1
Item2
<form runat="server">
<asp:BulletedList runat="server">
<asp:ListItem Text="Item1" />
<asp:ListItem Text="Item2" />
</asp:BulletedList>
</form>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
Text1
Text1
Text2
Text2
Text3
Text3
<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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
Item1
Item1
Item2
Item2
Item3
Item3
<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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
Item1
Item2
Item3
<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>
Item4
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
Mode
2.0
runat
1.0
Text
1.0
Examples
Literal
Declare one Literal control which displays some static text in an .aspx file.
Literal 2
Declare 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
Syntax
<asp:HyperLink Text="string" runat="server" />
Attribute
Description
string
Example
The following example sets the text for the Literal control:
<form runat="server">
<asp:Literal runat="server" Text="W3Schools" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
BackImageUrl
1.0
DefaultButton
2.0
Direction
2.0
GroupingText
2.0
HorizontalAlign
1.0
runat
1.0
ScrollBars
2.0
Wrap
1.0
Example
Panel
Declare one Panel control, one CheckBox control, and one Button control in an .aspx file. When the
user checks the CheckBox control, and the clicks the Refresh button, the Panel control will hide.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel BackImageUrl="URL" runat="server">
Some Content
</asp:Panel>
Attribute
Description
URL
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel DefaultButton="button_id" runat="server">
Some Content
</asp:Panel>
Attribute
Description
button_id
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel Direction="direction" runat="server">
Some Content
</asp:Panel>
Attribute
Description
direction
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel GroupingText="string" runat="server">
Some Content
</asp:Panel>
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel HorizontalAlign="align" runat="server">
Some Content
</asp:Panel>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Panel ScrollBars="value" runat="server">
Some Content
</asp:Panel>
Attribute
Description
value
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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 if
End Sub
</script>
Hello World!
<!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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
runat
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
AutoPostBack
A Boolean value that specifies whether the form should be posted immediately after the Checked property has
changed or not. Default is false
Checked
A Boolean value that specifies whether the radio button is checked or not
id
GroupName
OnCheckedChanged
The name of the function to be executed when the Checked property has changed
runat
Text
TextAlign
On which side of the radio button the text should appear (right or left)
Example
Radiobutton
Declare three RadioButton controls, 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 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 the
radiobutton 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
ASP Source:
<script runat="server">
Sub submit(Sender As Object,
if red.Checked then
Label1.Text="You selected "
elseIf green.Checked then
Label1.Text="You selected "
elseIf blue.Checked then
Label1.Text="You selected "
end if
End Sub
</script>
Output Result:
e As EventArgs)
& red.Text
& green.Text
Submit
& blue.Text
<!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>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
CellPadding
The amount of pixels between the border and the contents of the
table cell
1.0
CellSpacing
1.0
RepeatColumns
1.0
RepeatDirection
1.0
RepeatLayout
1.0
runat
Specifies that the control is a server control. Must be set to "server" 1.0
TextAlign
1.0
Example
RadiobuttonList
Declare one RadioButtonList control, one Button control, and one Label control in an .aspx file. Then we
create an event handler for the Click event which displays some text and the selected item, in a Label
control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
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 table
cell.
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:RadioButtonList CellSpacing="pixels" runat="server">
Some Content
</asp:RadioButtonList >
Attribute
Description
pixels
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:RadioButtonList RepeatColumns="num" runat="server">
Some Content
</asp:RadioButtonList >
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:RadioButtonList RepeatDirection="mode" runat="server">
Some Content
</asp:RadioButtonList >
Attribute
Description
mode
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:RadioButtonList RepeatLayout="mode" runat="server">
Some Content
</asp:RadioButtonList >
Attribute
Description
mode
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:RadioButtonList TextAlign="align" runat="server">
Some Content
</asp:RadioButtonList >
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
BulletImageUrl
2.0
BulletStyle
2.0
DisplayMode
2.0
FirstBulletNumber
2.0
runat
1.0
Target
2.0
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:BulletedList BulletImageUrl="url" runat="server">
Some Content
</asp:BulletedList>
Attribute
Description
url
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:BulletedList BulletStyle="style" runat="server">
Some Content
</asp:BulletedList>
Attribute
Description
style
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:BulletedList DisplayMode="mode" runat="server">
Some Content
</asp:BulletedList>
Attribute
Description
mode
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:BulletedList FirstBulletNumber="num" runat="server">
Some Content
</asp:BulletedList>
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:BulletedList Target="target" runat="server">
Some Content
</asp:BulletedList>
Attribute
Description
target
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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
BackColor
1.0
BorderColor
1.0
BorderStyle
1.0
BorderWidth
1.0
CssClass
1.0
Font
1.0
ForeColor
The foreground color (typically the color of the text) of the control
1.0
Height
1.0
RegisteredCssClass
2.0
Width
1.0
Created by www.ebooktutorials.blogspot.in
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 Demos
Set the background color of a Button control (with declaration and script)
Complete Style Control Reference
Created by www.ebooktutorials.blogspot.in
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 Demos
Set the border color of a Button control (with declaration and script)
Complete Style Control Referenc
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:webcontrol id="id" BorderStyle="style" runat="server" />
Description
Defines no border
Dotted
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
Inset
Outset
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 Demos
Set the border color of a Button control (with declaration and script)
Complete Style Control Reference
Created by www.ebooktutorials.blogspot.in
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:
Try-It-Yourself Demos
Set the border width of a Button control (with declaration and script)
Complete Style Control Reference
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:webcontrol id="id" CssClass="style" runat="server" />
Attribute
Description
style
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:webcontrol id="id" font-subproperty="value" runat="server" />
Font SubProperties
Value
Description
Bold
Italic
Name
Font name property (like "Verdana" or "Arial"). When you set this property, the Names property is automatically updated with a single element
array 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
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 Demos
Set the Font of a Button control (with declaration and script)
Complete Style Control Reference
Created by www.ebooktutorials.blogspot.in
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 Demos
Set the text color of a Button control (with declaration and script)
Complete Style Control Reference
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:webcontrol id="id" Width="value" runat="server" />
Attribute
Description
value
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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
BackImageUrl
1.0
Caption
2.0
CaptionAlign
2.0
CellPadding
1.0
CellSpacing
1.0
GridLines
1.0
HorizontalAlign
1.0
Rows
1.0
runat
1.0
Examples
Table
Declare two Table controls in an .aspx file.
Table 2
Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table BackImageUrl="URL" runat="server">
Some Content
</asp:Table>
Attribute
Description
URL
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table Caption="string" runat="server">
Some Content
</asp:Table>
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table Caption="text" CaptionAlign="align" runat="server">
Some Content
</asp:Table>
Attribute
Description
align
Example
The following example sets the Caption property in a table and aligns it to the bottom of the Table
control:
<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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table CellSpacing="px" runat="server">
Some Content
</asp:Table>
Attribute
Description
px
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table GridLines="mode" runat="server">
Some Content
</asp:Table>
Attribute
Description
mode
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Table HorizontalAlign="align" runat="server">
Some Content
</asp:Table>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
AssociatedHeaderCellID
2.0
ColumnSpan
1.0
HorizontalAlign
1.0
RowSpan
1.0
runat
1.0
Text
1.0
VerticalAlign
1.0
Wrap
1.0
Example
Table
Declare two Table controls in an .aspx file.
Table 2
Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableCell ColumnSpan="num" runat="server">
Some content
</asp:TableCell>
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableCell HorizontalAlign="align" runat="server">
Some Content
</asp:TableCell>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableCell RowSpan="num" runat="server">
Some content
</asp:TableCell>
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableCell Text="string" runat="server" />
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableCell VerticalAlign="align" runat="server">
Some Content
</asp:TableCell>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
Cells
HorizontalAlign
1.0
TableSection
2.0
VerticalAlign
1.0
Examples
Table
Declare two Table controls in an .aspx file.
Table 2
Declare a Table control, three TableRow controls, and two TableCell controls in an .aspx file.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableRow HorizontalAlign="align" runat="server">
Some Content
</asp:TableRow>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableRow TableSection="section" runat="server">
Some Content
</asp:TableRow>
Attribute
Description
section
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TableRow VerticalAlign="align" runat="server">
Some Content
</asp:TableRow>
Attribute
Description
align
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
1 2
3 4
<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>
1 2
3 4
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
dim rows,cells,j,i
rows=3
cells=2
For 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)
Next
End Sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:Table id="Table1" BorderWidth="1" GridLines="Both"
runat="server" />
</form>
</body>
</html>
Copyright: W3Schools.com
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
.NET
AutoCompleteType
2.0
AutoPostBack
1.0
CausesValidation
2.0
Columns
1.0
MaxLength
1.0
ReadOnly
1.0
Rows
1.0
runat
TagKey
Text
1.0
TextMode
1.0
ValidationGroup
Wrap
1.0
OnTextChanged
Examples
Textbox
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.
Textbox 2
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 copies the
contents of the textbox to the Label control.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TextBox AutoCompleteType="cat" runat="server"/>
Attribute
Description
cat
Example
The following example sets the AutoCompleteType mode to "FirstName":
<form runat="server">
<asp:TextBox id="tb1" runat="server" AutoCompleteType="FirstName" />
</form>
Show example
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TextBox Columns="num" runat="server" />
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TextBox runat="server" Rows="num" TextMode="MultiLine" />
Attribute
Description
num
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
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:TextBox Text="string" runat="server" />
Attribute
Description
string
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
Created by www.ebooktutorials.blogspot.in
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 box
MultiLine - Text box with multiple lines
Password - 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
Created by www.ebooktutorials.blogspot.in
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Your name is " & txt1.Text
End 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>
Copyright: W3Schools.com
Submit
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<script runat="server">
sub submit(sender As Object, e As EventArgs)
lbl1.Text=txt1.Text
end sub
</script>
Hello World!
Copy Text to Label
<!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
Properties
Property
Description
.NET
ClientID
Controls
Document
1.0
DocumentContent
1.0
DocumentSource
1.0
EnableTheming
runat
1.0
SkinID
Transform
1.0
TransformArgumentList
TransformSource
XPathNavigator
Example
XML
How to use the Xml control to display the result of an XSL Transform.
Web Server Controls
Created by www.ebooktutorials.blogspot.in
Syntax
<asp:Xml DocumentSource="path" runat="server" />
Attribute
Description
path
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
Created by www.ebooktutorials.blogspot.in
ASP Source:
Output Result:
<!DOCTYPE html>
<html>
<body>
My CD Collection
<form runat="server">
<asp:Xml DocumentSource="cdcatalog.xml"
TransformSource="cdcatalog.xsl" runat="server" />
</form>
Title
Empire Burlesque
Hide your heart
Greatest Hits
</body>
</html>
Copyright: W3Schools.com
Artist
Bob Dylan
Bonnie Tyler
Dolly Parton
Created by www.ebooktutorials.blogspot.in
Next Chapter
Description
CompareValidator
CustomValidator
RangeValidator
Checks that the user enters a value that falls between two
values
RegularExpressionValidator
RequiredFieldValidator
ValidationSummary
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
BackColor
ControlToCompare
ControlToValidate
Display
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error
message 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 input
passes validation.
Dynamic (the control displays an error message if validation
fails. Space is not reserved on the page for the message if the
input passes validation
EnableClientScript
Enabled
ErrorMessage
ForeColor
id
IsValid
Operator
runat
Text
Type
Specifies the data type of the values to compare. The types are:
Currency
Date
Double
Integer
String
ValueToCompare
Examples
CompareValidator
Declare two TextBox controls, one Button control, and one CompareValidator control in an .aspx file. If
validation fails, the text "Validation Failed!" will be displayed in red on a yellow background in the
CompareValidator control.
CompareValidator 2
Declare two TextBox controls, one ListBox control, one Button control, and one CompareValidator
control in an .aspx file. The check_operator() function sets the operator of the CompareValidator
control equal to the selected operator in the ListBox control, then it validates the CompareValidator
control. If validation fails, the text "Validation Failed!" will be displayed in red on a yellow background in
the CompareValidator control.
Validation Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
BackColor
ClientValidationFunction
ControlToValidate
Display
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error
message 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 input
passes validation.
Dynamic (the control displays an error message if validation
fails. Space is not reserved on the page for the message if the
input passes validation
EnableClientScript
Enabled
ErrorMessage
ForeColor
id
IsValid
OnServerValidate
runat
Text
Example
CustomValidator
Declare two Label controls, one TextBox control, one Button control, and one CustomValidator control
in an .aspx file. The user() function checks the length of the input value. If the length is <8 or >16 the
text "A username must be between 8 and 16 characters!" will appear in the CustomValidator control.
Validation Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
BackColor
ControlToValidate
Display
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error message
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 input passes
validation.
Dynamic (the control displays an error message if validation fails.
Space is not reserved on the page for the message if the input
passes validation
EnableClientScript
Enabled
ErrorMessage
ForeColor
id
IsValid
MaximumValue
MinimumValue
runat
Type
Specifies the data type of the value to check. The types are:
Currency
Date
Double
Integer
String
Text
Examples
RangeValidator
Declare one TextBox control, one Button control, and one RangeValidator control in an .aspx file. If
validation fails, the text "The date must be between 1/1/2002 and 31/5/2002!" will be displayed in the
RangeValidator control.
RangeValidator 2
Declare one TextBox control, one Button control, one Label control, and one RangeValidator control in
an .aspx file. The submit() function checks if the page is valid. If it is valid, it returns "The page is
valid!" in the Label control. If it is not valid, it returns "The page is not valid!" in the Label control. If
validation fails, the text "The value must be from 1 to 100!" will be displayed in the RangeValidator
control.
Validation Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
BackColor
ControlToValidate
Display
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error
message 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 input
passes validation.
Dynamic (the control displays an error message if validation
fails. Space is not reserved on the page for the message if the
input passes validation
EnableClientScript
Enabled
ErrorMessage
ForeColor
id
IsValid
runat
BackColor
Text
ValidationExpression
Example
RegularExpressionValidator
Declare one TextBox control, one Button control, one Label control, and one
RegularExpressionValidator control in an .aspx file. The submit() function checks if the page is valid. If
it is valid, it returns "The page is valid!" in the Label control. If it is not valid, it returns "The page is
not valid!" in the Label control. If validation fails, the text "The zip code must be 5 numeric digits!" will
be displayed in the RegularExpressionValidator control.
Validation Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
BackColor
ControlToValidate
Display
The display behavior for the validation control. Legal values are:
None (the control is not displayed. Used to show the error
message 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 input
passes validation.
Dynamic (the control displays an error message if validation
fails. Space is not reserved on the page for the message if the
input passes validation
EnableClientScript
Enabled
ErrorMessage
ForeColor
id
InitialValue
Specifies the starting value of the input control. Default value is ""
IsValid
runat
Text
Example
RequiredFieldValidator
Declare two TextBox controls, one Button control, and one RequiredFieldValidator control in an .aspx
file. It shows how to use the RequiredFieldValidator control to make the "txt_name" textbox a required
field.
Validation Server Controls
Created by www.ebooktutorials.blogspot.in
Properties
Property
Description
DisplayMode
EnableClientScript
Enabled
ForeColor
HeaderText
id
runat
ShowMessageBox
ShowSummary
Examples
Validationsummary
Use the ValidationSummary control to write a bulleted list of fields that are required but left empty by
the user.
Validationsummary 2
Use the ValidationSummary control to display a message box of the fields that are required but left
empty by the user.
Validation Server Controls