Asp MVC
Asp MVC
NET Tutorial
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:
Web Pages
Single Pages Model
Simplest ASP.NET model. Similar to PHP and classic ASP. Built-in templates and helpers for database, video, graphics, social media and more.
MVC
Model View Controller
MVC separates web applications into 3 different components: Models for data Views for display Controllers for input
Web Forms
Event Driven Model
The traditional ASP.NET event driven development model: Web pages with added server controls, server events, and server code.
WebMatrix
Web Editor for Web Pages
ASP.NET Framework
.NET is a framework for developing virtually any type of computer application. The ASP.NET framework is the part of .NET designed for creating web applications.
MVC Tutorial
MVC is a model for building web applications using a MVC (Model View Controller) design. If you want a lighter alternative to traditional ASP.NET, MVC is the place to start. In our MVC tutorial you will learn how to build web applications using a lightweight development model, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.
If you are a professional web developer with prior ASP.NET experience, you can still learn a lot, since these tutorials covers a lot new concepts of ASP.NET, like HTML5, CSS3, JQuery, and more.
ASP.NET
Classic ASP - Active Server Pages
Active Server Pages (ASP), also known as Classic ASP, was introduced in 1998 as Microsoft's first server side scripting engine. ASP is a technology that enables scripts in web pages to be executed by an Internet server. ASP pages have the file extension .asp, and are normally written in VBScript. If you want to learn Classic ASP,
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.
Web Pages (with Razor syntax) MVC (Model View Controller) Web Forms (traditional ASP.NET)
This tutorial uses WebMatrix for Web Pages, and Visual Web Developer for MVC and Web Forms.
Create a web site Add files and folders Add a consistent look Add navigation Add a database Add login and security
Web Pages examples and templates A web server language (Razor using VB or C#) A web server (IIS Express) A database server (SQL Server Compact) A web server markup language (Razor) A full web development framework (ASP.NET)
If you install WebMatrix, you will get the full benefits from this tutorial. With WebMatrix you can start from scratch with an empty web site and a blank page, or build on open source applications from a "Web Application Gallery". Both PHP and ASP.NET applications are available, such as Umbraco, DotNetNuke, Drupal, Joomla, WordPress and many more. WebMatrix also has built-in tools for security, search engine optimization, and web publishing. The skills and code you develop with WebMatrix can seamlessly be transformed to fully professional ASP.NET applications.
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.
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):
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, typedefault.cshtml:
10
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:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Web Pages Demo</title> </head> <body> <h1>Hello Web Pages</h1> </body> </html>
11
WebMatrix starts a web server (IIS Express) and runs the page on your computer. The page is displayed in your default browser:
12
What We Will Do
In this chapter we will:
a new empty web site the necessary folders a standard style sheet for the site a standard layout for the site a home page for the site
Start WebMatrix Click on "Create Site From Template" Choose "Empty Site" Name the site "Demo"
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
13
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: 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"
14
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.
15
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.
16
What We Will Do
In this chapter we will:
_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.
17
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).
18
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).
19
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.
20
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>
21
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":
22
Rename the database to "SmallBakery.sdf". Click New Table. Click New Column and create 4 columns named "Id", "Name", "Description", and "Price". For all columns, set Allows Null to "False". For the "Id" column, Set Data Type to "bigint", Is Identity to "True", and Is Primary Key to "True". For the "Name" and "Description" columns, set Data Type to "nvarchar". For the "Price" column, set Data Type to "money". Save the table and name it "Product". When you are finished, your table design will look like this:
23
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)
24
Made with organic strawberries Second only to your mom's pie If you like pecans, this is for you Made with the best lemons in the world Your kids will love these
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 align="right">@row.Price</td> </tr> } </table> </body> </html>
25
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.
26
27
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
Select the Databases workspace in WebMatrix, and click "Add a database to your site" to create a new SQL Server Compact database. Name the database "Users.sdf" The database will be created in the App_Data folder of your web.
28
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, thedatabase itself must always exist.
29
Site.css
/* Forms --------------------*/ fieldset label { display:block; padding:4px; } input[type="text"],input[type="password"] { width:300px; } input[type="submit"] { padding:4px; }
30
{ 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>
31
Login.cshtml
@{// Initialize page var username = ""; 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>
32
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.
33
What We Will Do
In this chapter we will:
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.
34
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.
35
WP Tutorial
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
Web Forms
36
Easy to learn, understand, and use Built around single web pages Similar to PHP and Classic ASP Server scripting with Visual Basic or C# Full HTML, CSS, and JavaScript control
Web Pages are easy extendable with programmable Web Helpers, including database, video, graphics, social networking and much more.
Where to Start?
Many developers like to start learning a new technology by looking at working examples. If you want to take a look at a working Web Pages examples, follow the ASP.NET Web Pages Demo.
37
38
What is Razor?
Razor Razor Razor Razor is a markup syntax for adding server-based code to web pages has the power of traditional ASP.NET markup, but is easier to learn, and easier to use is a server side markup syntax much like ASP and PHP supports C# and Visual Basic programming languages
<!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
39
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
40
Example
<!-- Single statement block --> @Code dim myMessage = "Hello World" End Code <!-- Inline expression or variable --> <p>The value of myMessage is: @myMessage</p> <!-- Multi-statement block --> @Code dim greeting = "Welcome to our site!" dim weekDay = DateTime.Now.DayOfWeek dim greetingMessage = greeting & " Today is: " & weekDay End Code <p>The greeting is: @greetingMessage</p>
Run example
41
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
42
Layout Page:
<html> <body> <p>This is header text</p> @RenderBody() <p>© 2012 W3Schools. All rights reserved.</p> </body> </html>
43
_AppStart.cshtml
@{ WebMail.SmtpServer = "mailserver.example.com"; WebMail.EnableSsl = true; WebMail.UserName = "[email protected]"; WebMail.Password = "your-password"; WebMail.From = "[email protected]"; }
44
About Logical and Physical folder structures About Virtual and Physical names About web URLs and Paths
"Account" folder contains logon and security files "App_Data" folder contains databases and data files "Images" folder contains images "Scripts" folder contains browser scripts "Shared" folder contains common files (like layout and style files)
45
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.
46
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:
@{var myStyleSheet = "~/Shared/Site.css";} <!-- This creates a link to the CSS file. --> <link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" /> <!-- Same as : --> <link rel="stylesheet" type="text/css" href="/Shared/Site.css" />
The Href method is a method of the WebPage Object.
47
48
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.
49
Run example
50
Razor Example
@{ var imagePath=""; if (Request["Choice"] != null) {imagePath="images/" + Request["Choice"];} } <!DOCTYPE html> <html> <body> <h1>Display Images</h1> <form method="post" action="">
51
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.
52
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. 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.
53
@RenderPage("header.cshtml") @RenderBody()
In the previous chapter you saw two Page Object properties being used (isPost, and Request):
RenderPage(page)
RenderSection(section) Renders the content of a named section (In layout pages) Write(object) WriteLitteral Writes the object as an HTML-encoded string Writes an object without HTML-encoding it first.
54
The pages property is very helpful. For instance, it makes it possible to set the page title in content files, and use it in the layout file:
Home.cshtml
@{ Layout="~/Shared/Layout.cshtml"; Page.Title="Home Page" } <h1>Welcome to W3Schools</h1> <h2>Web Site Main Ingredients</h2> <p>A Home Page (Default.cshtml)</p> <p>A Layout File (Layout.cshtml)</p> <p>A Style Sheet (Site.css)</p>
55
Layout.cshtml
<!DOCTYPE html> <html> <head> <title>@Page.Title</title> </head> <body> @RenderBody() </body> </html
56
Persons.txt
George,Lucas Steven,Spielberg Alfred,Hitchcock
57
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
58
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.
59
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:
Automatically sets up an HTML table to display data Supports different options for formatting Supports paging (First, next, previous, last) through data Supports sorting by clicking on column headings
60
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. In WebMatrix, open the Site workspace. Click on Web Pages Administration. Login to Web Pages Administration using a password *. Search for helpers using the search field. Click install to install your desired helpers.
(* the first time you use Web Pages Administration, it will prompt you to create a password)
61
62
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
63
Automatically sets up an HTML table to display data Supports different options for formatting Supports paging through data Supports Sorting by clicking on column headings
WebGrid Example
@{ var db = Database.Open("SmallBakery") ; var selectQueryString = "SELECT * FROM Product ORDER BY Id"; var data = db.Query(selectQueryString); var grid = new WebGrid(data); } <html> <head> <title>Displaying Data Using the WebGrid Helper</title> </head> <body> <h1>Small Bakery Products</h1> <div id="grid"> @grid.GetHtml()
64
Run example
65
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(); }
66
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");
67
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 - 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:
68
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
69
dataSet.ReadXml(Server.MapPath("data.xml")); var dataView = new DataView(dataSet.Tables[0]); var myChart = new Chart(width: 600, height: 400) .AddTitle("Sales Per Employee") .AddSeries("Default", chartType: "Pie", xValue: dataView, xField: "Name", yValues: dataView, yFields: "Sales") .Write();} }
Run example
70
_AppStart.cshtml
@{ WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true); }
To initiate the WebMail helper, add the the following WebMail properties to your AppStart page:
_AppStart.cshtml
@{ WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true); WebMail.SmtpServer = "smtp.example.com"; WebMail.SmtpPort = 25; WebMail.EnableSsl = false; WebMail.UserName = "[email protected]"; WebMail.Password = "password-goes-here";
71
WebMail.From = "[email protected]"; }
Properties explained: SmtpServer: The name the SMTP server that will be used to send the emails. SmtpPort: The port the server will use to send SMTP transactions (emails). EnableSsl: True, if the server should use SSL (Secure Socket Layer) encryption. UserName: The name of the SMTP email account used to send the email. Password: The password of the SMTP email account. From: The email to appear in the from address (often the same as UserName).
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.
72
Email_Send.cshtml
@{ // Read input var customerEmail = Request["customerEmail"]; var customerRequest = Request["customerRequest"]; try { // Send email WebMail.Send(to:"[email protected]", subject: "Help request from - " + customerEmail, body: customerRequest ); } catch (Exception ex ) { <text>@ex</text> } }
For more information about sending emails from a ASP.NET Web Pages application, please see the:WebMail Object Reference.
73
74
index.php
<!DOCTYPE html> <html> <body> <?php phpinfo(); ?> </body> </html>
Run the file and see PHP at work.
75
76
Copy everything from your folder: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies to your application's bin folder on the remote server.
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>
77
Examples in C#
Basic Web Pages Display Date and Time Reusable Header and Footer Basic HTML Form Examples Explained Basic C# For Loop For Each Loop While Loop Array If Condition If Else Condition Else If Condition Switch Condition Examples Explained Working with Databases Display Database Data Display Data with WebGrid Examples Explained Using the Chart Helper Display Display Display Display a a a a Bar Chart from an Array Bar Chart from a Database Pie Chart from a Database Pie Chart from an XML File
Examples in VB
Basic Web Pages Display Date and Time Reusable Header and Footer Basic HTML Form Examples Explained Basic VB For Loop For Each Loop While Loop Array If Condition If Else Condition Else If Condition Select Condition Examples Explained Working with Databases Display Database Data Display Data with WebGrid Examples Explained Using the Chart Helper Display Display Display Display a a a a Bar Chart from an Array Bar Chart from a Database Pie Chart from a Database Pie Chart from an XML File
Examples Explained
Examples Explained
78
WP References
AsDateTime(), AsDateTime(value)
AsDecimal(), AsDecimal(value)
AsFloat(), AsFloat(value)
AsInt(), AsInt(value)
Html.Raw(value)
79
Returns true if the value can be converted from a string to the specified type. Returns true if the object or variable has no value. Returns true if the request is a POST. (Initial requests are usually a GET.) Specifies the path of a layout page to apply to this page. 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: (Layout pages) Renders the content of a content page that is not in any named sections. 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. Setrequired to false to make a section optional. Gets or sets the value of an HTTP cookie. Gets the files that were uploaded in the current request. Gets data that was posted in a form (as strings). Request[key] checks both the Request.Form and the Request.QueryString collections.
IsEmpty()
IsPost
Layout
RenderBody()
Request.Cookies[key]
Request.Files[key]
Request.Form[key]
80
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) Selectively disables request validation Request.Unvalidated().QueryString|Form|Cookies|Headers[key] for a form element, query-string value, cookie, or header value. Request validation is enabled by default and prevents users from posting markup or other potentially dangerous content. Response.AddHeader(name, value) Adds an HTTP server header to the response. Caches the page output for a specified time. Optionally setsliding to reset the timeout on each page access andvaryByParams to cache different versions of the page for each different query string in the page request. Redirects the browser request to a new location. Sets the HTTP status code sent to the browser. Writes the contents of data to the response with an optional MIME type. Writes the contents of a file to the response. (Layout pages) Defines a content section that has a name. Decodes a string that is HTML encoded. Encodes a string for rendering in HTML markup. Returns the server physical path for the specified virtual path.
Response.Redirect(path)
Response.SetStatus(httpStatusCode)
Response.WriteBinary(data [, mimetype])
Response.WriteFile(file)
@section(sectionName) { content }
Server.HtmlDecode(htmlText)
Server.HtmlEncode(text)
Server.MapPath(virtualPath)
81
Decodes text from a URL. Encodes text to put in a URL. Gets or sets a value that exists until the user closes the browser. Displays a string representation of the object's value. Gets additional data from the URL (for example, /MyPage/ExtraData).
ToString()
UrlData[index]
82
83
InitializeDatabaseConnection() IsConfirmed() IsCurrentUser() Login() Logout() RequireAuthenticatedUser() RequireRoles() RequireUser() ResetPassword() UserExists()
Initializes the WebSecurity system (database) Checks if a user is confirmed Checks if the current user matches a user name Logs the user in by setting a token in the cookie Logs the user out by removing the token cookie Exits the page if the user is not an authenticated user Exits the page if the user is not a part of the specified roles Exits the page if the user is not the specified user Changes a user's password using a token Checks if a given user exists
Technical Data
Name Class Namespace Assembly Value WebMatrix.WebData.WebSecurity WebMatrix.WebData WebMatrix.WebData.dll
84
_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). "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.
The Membership table will contain membership information about when the user was created and if (and when) the membership was confirmed.
85
Confirmation Is Last Password Token Confirmed Password Failure NULL True NULL
Password Change
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.
86
Description Executes SQLstatement (with optional parameters) such as INSERT, DELETE, or UPDATE and returns a count of affected records. Returns the identity column from the most recently inserted row. Opens either the specified database file or the database specified using a named connection string from the Web.config file.
Database.GetLastInsertId()
Database.Open(filename) Database.Open(connectionStringName)
Database.OpenConnectionString(connectionString) Opens a database using the connection string. (This contrasts with Database.Open, which uses a connection string name.) Database.Query(SQLstatement[, parameters]) Queries the database using SQLstatement(optionally passing parameters) and returns the results as a collection. Executes SQLstatement (with optional parameters) and returns a single record. Executes SQLstatement (with optional parameters) and returns a single value.
87
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.
88
The Send() method has the following parameters: Parameter to subject body Type String String String Description The Email recipients (separated by semicolon) The subject line The body of the message
And the following optional parameters: Parameter from cc filesToAttach isBodyHtml additionalHeaders Type String String Collection Boolean Collection Description The email of the sender The cc emails (separated by semicolon) Filenames True if the email body is in HTML Additional headers
Technical Data
Name Class Namespace Assembly Value System.Web.Helpers.WebMail System.Web.Helpers System.Web.Helpers.dll
89
corporate network, your IT department can give you the name. If you are working at home, you might be able to use your ordinary email provider. In order to send an email you will need:
The name of the SMTP server The port number (most often 25) An email user name An email password
In the root of your web, create a page (or edit the page ) named _AppStart.cshtml. Put the following code inside the file:
_AppStart.cshtml
@} WebMail.SmtpServer = "smtp.example.com"; WebMail.SmtpPort = 25; WebMail.EnableSsl = false; WebMail.UserName = "[email protected]"; WebMail.Password = "password"; WebMail.From = "[email protected]" }
The code above will run each time the web site (application) starts. It feeds your WebMail Objectwith initial values. Please substitute: smtp.example.com with the name the SMTP server that will be used to send the emails. 25 with the port number the server will use to send SMTP transactions (emails). false with true, if the server should use SSL (Secure Socket Layer) encryption. [email protected] with the name of the SMTP email account used to send emails. password with the password of the SMTP email account. john@example with the email to appear in the from address. You don't have to initiate the WebMail object in your AppStart file, but you must set these properties before you call the WebMail.Send() method.
90
Analytics.GetStatCounterHtml(project, security)
Analytics.GetYahooHtml(account)
91
Chart.AddSeries([name] [, chartType] [, Adds a series of values to the chart. chartArea] [, axisLabel] [, legend] [, markerStep] [, xValue] [, xField] [, yValues] [, yFields] [, options])
92
Json.Decode(string)
93
ModelStateDictionary.AddError(key, errorMessage) Associates an error message with a form field. Use the ModelState helper to access this member. ModelStateDictionary.AddFormError(errorMessage) Associates an error message with a form. Use the ModelState helper to access this member. ModelStateDictionary.IsValid Returns true if there are no validation errors. Use the ModelState helper to access this member.
Sets public and private keys for the reCAPTCHA service. Normally you set these properties in the_AppStart page. Returns the result of the reCAPTCHA test. Renders status information about ASP.NET Web Pages.
94
WebCache.Remove(key)
95
WebGrid.GetHtml() WebGrid.Pager()
Loads an image when an image is posted to a page during a file upload. Resizes the image. Rotates the image to the left or the right.
96
ASP.NET Razor
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> <?php for ($i = 0; $i < 10; $i++) { echo("<li>$i</li>"); } ?> </ul>
97
<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
98
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
99
Example
<!-- Single statement block --> @Code dim myMessage = "Hello World" End Code <!-- Inline expression or variable --> <p>The value of myMessage is: @myMessage</p> <!-- Multi-statement block --> @Code dim greeting = "Welcome to our site!" dim weekDay = DateTime.Now.DayOfWeek dim greetingMessage = greeting & " Today is: " & weekDay End Code <p>The greeting is: @greetingMessage</p>
100
Run example
101
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
102
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
103
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>
104
Run example
105
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 int float Description Integer (whole numbers) Floating-point number Examples 103, 12, 5168 3.14, 3.4e38
106
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 of common operators: Operator = + * / += -= == != < > <= >= + . () () [] Description Assigns a value to a variable. Adds a value or variable. Subtracts a value or variable. Multiplies a value or variable. Divides a value or variable. Increments a variable. Decrements a variable. Equality. Returns true if values are equal. Inequality. Returns true if values are not equal. Less than. Greater than. Less than or equal. Greater than or equal. Adding strings (concatenation). Dot. Separate objects and methods. Parenthesis. Groups values. Parenthesis. Passes parameters. Brackets. Accesses values in arrays or collections. Example i=6 i=5+5 i=5-5 i=5*5 i=5/5 i += 1 i -= 1 if (i==10) if (i!=10) if if if if (i<10) (i>10) (i<=10) (i>=10)
107
! && ||
AsDateTime() Converts a string to an ASP.NET DateTime type. IsDateTime() AsBool() IsBool() ToString() Converts a string to a Boolean.
108
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>
109
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;
110
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
111
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)
112
{ <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>
low.</p>
Run example
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.
113
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.
114
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 integer double Description Integer (whole numbers) 64 bit floating-point number Examples 103, 12, 5168 3.14, 3.4e38
115
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 Assigns a value to a variable. Adds a value or variable. Subtracts a value or variable. Multiplies a value or variable. Divides a value or variable. Increments a variable. Decrements a variable. Equality. Returns true if values are equal. Inequality. Returns true if values are not equal. Less than. Greater than. Less than or equal. Greater than or equal. Adding strings (concatenation). Dot. Separate objects and methods. Parenthesis. Groups values. Parenthesis. Passes parameters. Parenthesis. Accesses values in arrays or collections. Example i=6 i=5+5 i=5-5 i=5*5 i=5/5 i += 1 i -= 1 if i=10 if <>10 if if if if i<10 i>10 i<=10 i>=10
116
Not. Reverses true or false. Logical AND. Logical OR. Extended Logical AND. Extended Logical OR.
if Not ready if ready And clear if ready Or clear if ready AndAlso clear if ready OrElse clear
AsFloat() IsFloat()
AsDecimal() IsDecimal()
AsDateTime() Converts a string to an ASP.NET DateTime type. IsDateTime() AsBool() IsBool() ToString() Converts a string to a Boolean.
117
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>
118
</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
119
@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> </body> </html>
Run example
120
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
121
<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
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 or else if conditions are true, the last else block (without a condition) covers "everything else".
122
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.
123
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 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.
124
The business layer (Model logic) The display layer (View logic) The input control (Controller logic)
The Model is the part of the application that handles the logic for the application data. Often model objects retrieve data (and store data) from a database. The View is the parts of the application that handles the display of the data. Most often the views are created from the model data. The Controller is the part of the application that handles user interaction. Typically controllers read data from a view, control user input, and send input data to the model. The MVC separation helps you manage complex applications, because you can focus on one aspect 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.
125
Visual Web Developer is a development tool tailor made for MVC (and Web Forms). Visual Web Developer contains:
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.
126
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.
127
Open the Visual C# templates Select the template ASP.NET MVC 3 Web Application Set the project name to MvcDemo Set the disk location to something like c:\w3schools_demo Click OK
Select the Internet Application template Select the Razor Engine Select HTML5 Markup Click OK
128
We will explore the content of the files and folders in the next chapter of this tutorial.
129
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:
130
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.
131
Visual Web Developer has created a Home controller (for the Home and the About page) and an Account controller (for Login pages):
132
We will edit the layout files in the next chapter of this tutorial.
133
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3 features in the application.
134
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")"></script> <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></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>
135
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
136
{ color: #034af3; } /* Menu Styles ------------------------------*/ 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; /*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;
137
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.
138
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.
139
namespace MvcDemo.Controllers { public class HomeController : Controller { public ActionResult Index() {return View();} public ActionResult About() {return View();} } }
140
141
142
@{ViewBag.Title = "Home Page";} <h1>Welcome to W3Schools</h1> <p>Put Home Page content here</p>
143
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.
144
Right-click the App_Data folder in the Solution Explorer window Select Add, New Item Select SQL Server Compact Local Database * Name the database Movies.sdf. Click the Add button
* If SQL Server Compact Local Database is not an option, you have not installed SQL Server Compact on your computer. Install it from this link: SQL Server Compact Visual Web Developer automatically creates the database in the App_Data folder. Note: In this tutorial it is expected that you have some knowledge about SQL databases. If you want to study this topic first, please visit our SQL Tutorial.
145
Date
datetime
No
Columns explained: ID is an integer (whole number) used to identify each record in the table. Title is a 100 character text column to store the name of the movie. Director is a 100 character text column to store the director's name. Date is a datetime column to store the release date of the movie. After creating the columns described above, you must make the ID column the table's primary key (record identifier). To do this, click on the column name (ID) and select Primary Key. Also, in theColumn Properties window, set the Identity property to True:
When you have finished creating the table columns, save the table and name it MovieDBs.
146
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.
Note: The ID column is updated automatically. You should not edit it.
147
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.
In the Solution Explorer, right-click the Models folder, and select Add and Class. Name the class MovieDB.cs, and click Add. Edit the class:
148
int ID { get; set; } string Title { get; set; } string Director { get; set; } DateTime Date { get; set; }
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller Set controller name to MoviesController Select template: Controller with read/write actions and views, using Entity Framework Select model class: MovieDB (McvDemo.Models) Select data context class: MovieDBContext (McvDemo.Models) Select views Razor (CSHTML) Click Add
A MoviesController.cs file in the Controllers folder A Movies folder in the Views folder
149
150
public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } }
151
[Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } }
152
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:
153
The Html.ActionLink() helper as several properties: Property .linkText .actionName .routeValues .controllerName .htmlAttributes .protocol .hostname .fragment Description The link text (label) The target action The values passed to the action The target controller The set of attributes to the link The link protocol The host name for the link The anchor target for the link
Note: You can pass values to a controller action. For example, you can pass the id of a database record to a database edit action: Razor Syntax C#:
154
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()){%> <p> <label for="FirstName">First Name:</label> <%= Html.TextBox("FirstName") %> <%= Html.ValidationMessage("FirstName", "*") %> </p> <p> <label for="LastName">Last Name:</label> <%= Html.TextBox("LastName") %> <%= Html.ValidationMessage("LastName", "*") %> </p> <p> <label for="Password">Password:</label> <%= Html.Password("Password") %> <%= Html.ValidationMessage("Password", "*") %> </p> <p> <label for="Password">Confirm Password:</label> <%= Html.Password("ConfirmPassword") %> <%= Html.ValidationMessage("ConfirmPassword", "*") %> </p> <p> <label for="Profile">Profile:</label> <%= Html.TextArea("Profile", new {cols=60, rows=10})%> </p> <p> <%= Html.CheckBox("ReceiveNewsletter") %> <label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label> </p> <p> <input type="submit" value="Register" /> </p> <%}%>
155
156
Copy everything from your folders: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies to your application's bin folder on the remote server.
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>
157
ActionDescriptor
ActionExecutedContext
ActionExecutingContext
ActionFilterAttribute ActionMethodSelectorAttribute
ActionNameAttribute
ActionNameSelectorAttribute
ActionResult
AdditionalMetadataAttribute
AjaxHelper
AjaxHelper(Of TModel)
AjaxRequestExtensions
158
an AJAX request. AllowHtmlAttribute Allows a request to include HTML markup during model binding by skipping request validation for the property. (It is strongly recommended that your application explicitly check all models where you disable request validation in order to prevent script exploits.) Provides a way to register one or more areas in an ASP.NET MVC application. Encapsulates the information that is required in order to register an area within an ASP.NET MVC application. Provides an abstract class to implement a metadata provider. Provides an abstract class for classes that implement a validation provider. Provides the base class for asynchronous controllers. Represents an attribute that is used to set the timeout value, in milliseconds, for an asynchronous method. Encapsulates the information that is required for using an AuthorizeAttribute attribute. Represents an attribute that is used to restrict access by callers to an action method. Represents an attribute that is used to provide details about how model binding to a parameter should occur. Represents the base class for views that are compiled by the BuildManager class before being rendered by a view engine. Provides a base class for view engines. Maps a browser request to a byte array. Represents an attribute that is used to indicate that an action method should be called only as a child action. Represents a value provider for values from child actions. Represents a factory for creating value provider objects for
AreaRegistration
AreaRegistrationContext
AssociatedMetadataProvider AssociatedValidatorProvider
AsyncController AsyncTimeoutAttribute
AuthorizationContext
AuthorizeAttribute
BindAttribute
BuildManagerCompiledView
ChildActionValueProvider ChildActionValueProviderFactory
159
child actions. ClientDataTypeModelValidatorProvider CompareAttribute Returns the client data-type model validators. Provides an attribute that compares two properties of a model. Represents a user-defined content type that is the result of an action method. Provides methods that respond to HTTP requests that are made to an ASP.NET MVC Web site. Represents a class that is responsible for invoking the action methods of a controller. Represents the base class for all MVC controllers. Represents a class that is responsible for dynamically building a controller. Encapsulates information about an HTTP request that matches specified RouteBase and ControllerBase instances. Encapsulates information that describes a controller, such as its name, type, and actions. Adds the controller to the FilterProviderCollection instance. Represents an attribute that invokes a custom model binder. Provides a container for common metadata, for the DataAnnotationsModelMetadataProvider class, and for the DataAnnotationsModelValidator class for a data model.
ContentResult
Controller
ControllerActionInvoker
ControllerBase ControllerBuilder
ControllerContext
ControllerDescriptor
DataAnnotationsModelMetadataProvider Implements the default model metadata provider for ASP.NET MVC. DataAnnotationsModelValidator DataAnnotationsModelValidator(Of TAttribute) Provides a model validator. Provides a model validator for a specified validation type.
DataAnnotationsModelValidatorProvider Implements the default validation provider for ASP.NET MVC. DataErrorInfoModelValidatorProvider Provides a container for the error-information model
160
validator. DefaultControllerFactory DefaultModelBinder Represents the controller factory that is registered by default. Maps a browser request to a data object. This class provides a concrete implementation of a model binder. Represents a memory cache for view locations. Provides a registration point for dependency resolvers that implement IDependencyResolver or the Common Service Locator IServiceLocator interface. Provides a type-safe implementation of GetService and GetServices. Represents the base class for value providers whose values come from a collection that implements the IDictionary(Of TKey, TValue) interface. Provides an empty metadata provider for data models that do not require metadata. Provides an empty validation provider for models that do not require a validator. Represents a result that does nothing, such as a controller action method that returns nothing. Provides the context for using the HandleErrorAttribute class. Provides a helper class to get the model name from an expression. Provides a container for client-side field validation metadata. Sends the contents of a binary file to the response. Sends the contents of a file to the response. Represents a base class that is used to send binary file content to the response. Sends binary content to the response by using a Stream instance.
DefaultViewLocationCache DependencyResolver
DependencyResolverExtensions
DictionaryValueProvider(Of TValue)
EmptyModelMetadataProvider
EmptyModelValidatorProvider
EmptyResult
ExceptionContext ExpressionHelper
FileStreamResult
161
Filter
Represents a metadata class that contains a reference to the implementation of one or more of the filter interfaces, the filter's order, and the filter's scope. Represents the base class for action and result filter attributes. Defines a filter provider for filter attributes. Encapsulates information about the available action filters. Represents the collection of filter providers for the application. Provides a registration point for filters. Contains the form value providers for the application. Encapsulates information that is required in order to validate and process the input data from an HTML form. Represents a value provider for form values that are contained in a NameValueCollection object. Represents a class that is responsible for creating a new instance of a form-value provider object. Represents a class that contains all the global filters. Represents the global filter collection. Represents an attribute that is used to handle an exception that is thrown by an action method. Encapsulates information for handling an error that was thrown by an action method. Represents an attribute that is used to indicate whether a property or field value should be rendered as a hidden input element. Represents support for rendering HTML controls in a view. Represents support for rendering HTML controls in a strongly typed view.
FilterAttribute
FormValueProvider
FormValueProviderFactory
HandleErrorInfo
HiddenInputAttribute
162
HttpDeleteAttribute
Represents an attribute that is used to restrict an action method so that the method handles only HTTP DELETE requests. Represents a value provider to use with values that come from a collection of HTTP files. Represents a class that is responsible for creating a new instance of an HTTP file collection value provider object. Represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests. Defines an object that is used to indicate that the requested resource was not found. Represents an attribute that is used to restrict an action method so that the method handles only HTTP POST requests. Binds a model to a posted file. Represents an attribute that is used to restrict an action method so that the method handles only HTTP PUT requests. Extends the HttpRequestBase class that contains the HTTP values that were sent by a client during a Web request. Provides a way to return an action result with a specific HTTP response status code and description. Represents the result of an unauthorized HTTP request. Sends JavaScript content to the response. Represents a class that is used to send JSON-formatted content to the response. Enables action methods to send and receive JSON-formatted text and to model-bind the JSON text to parameters of action methods. Maps a browser request to a LINQ Binary object. Represents an attribute that is used to associate a model type to a model-builder type.
HttpFileCollectionValueProvider
HttpFileCollectionValueProviderFactory
HttpGetAttribute
HttpNotFoundResult
HttpPostAttribute
HttpPostedFileBaseModelBinder HttpPutAttribute
HttpRequestExtensions
HttpStatusCodeResult
JsonValueProviderFactory
LinqBinaryModelBinder ModelBinderAttribute
163
ModelBinderDictionary
Represents a class that contains all model binders for the application, listed by binder type. Provides a container for model binder providers. Provides a container for model binder providers. Provides global access to the model binders for the application. Provides the context in which a model binder functions. Provides a container for an equality validation rule that is sent to the browser. Provides a container for a range-validation rule that is sent to the browser. Provides a container for a regular-expression client validation rule that is sent to the browser. Provides a container for a remote validation rule that is sent to the browser. Provides a container for client validation for required field. Provides a base class container for a client validation rule that is sent to the browser. Provides a container for a string-length validation rule that is sent to the browser. Represents an error that occurs during model binding. A collection of ModelError instances. Provides a container for common metadata, for the ModelMetadataProvider class, and for the ModelValidator class for a data model. Provides an abstract base class for a custom metadata provider. Provides a container for the current ModelMetadataProvider instance.
ModelBindingContext ModelClientValidationEqualToRule
ModelClientValidationRangeRule
ModelClientValidationRegexRule
ModelClientValidationRemoteRule
ModelClientValidationRequiredRule ModelClientValidationRule
ModelClientValidationStringLengthRule
ModelMetadataProvider
ModelMetadataProviders
164
ModelState
Encapsulates the state of model binding to a property of an action-method argument, or to the argument itself. Represents the state of an attempt to bind a posted form to an action method, which includes validation information. Provides a container for a validation result. Provides a base class for implementing validation logic. Provides a list of validators for a model. Provides a container for a list of validation providers. Provides a container for the current validation provider. Represents a list of items that users can select more than one item from. When implemented in a derived class, provides a metadata class that contains a reference to the implementation of one or more of the filter interfaces, the filter's order, and the filter's scope. Selects the controller that will handle an HTTP request. Represents an HTML-encoded string that should not be encoded again. Verifies and processes an HTTP request. Creates an object that implements the IHttpHandler interface and passes the request context to it. Creates instances of MvcWebPageRazorHost files. Extends a NameValueCollection object so that the collection can be copied to a specified dictionary. Represents the base class for value providers whose values come from a NameValueCollection object. Provides a convenience wrapper for the AsyncTimeoutAttribute attribute. Represents an attribute that is used to indicate that a
ModelStateDictionary
MvcFilter
MvcHandler MvcHtmlString
MvcHttpHandler MvcRouteHandler
MvcWebRazorHostFactory NameValueCollectionExtensions
NameValueCollectionValueProvider
NoAsyncTimeoutAttribute
NonActionAttribute
165
controller method is not an action method. OutputCacheAttribute Represents an attribute that is used to mark an action method whose output will be cached. Encapsulates information for binding action-method parameters to a data model. Contains information that describes a parameter. Represents a base class that is used to send a partial view to the response. Provides a registration point for ASP.NET Razor preapplication start code. Represents a value provider for query strings that are contained in a NameValueCollection object. Represents a class that is responsible for creating a new instance of a query-string value-provider object. Provides an adapter for the RangeAttribute attribute. Represents the class used to create views that have Razor syntax. Represents a view engine that is used to render a Web page that uses the ASP.NET Razor syntax. Controls the processing of application actions by redirecting to a specified URI. Represents a result that performs a redirection by using the specified route values dictionary. Contains information that describes a reflected action method. Contains information that describes a reflected controller. Contains information that describes a reflected action-method parameter. Provides an adapter for the RegularExpressionAttribute attribute.
ParameterBindingInfo
ParameterDescriptor PartialViewResult
PreApplicationStartCode
QueryStringValueProvider
QueryStringValueProviderFactory
RangeAttributeAdapter RazorView
RazorViewEngine
RedirectResult
RedirectToRouteResult
ReflectedActionDescriptor
ReflectedControllerDescriptor ReflectedParameterDescriptor
RegularExpressionAttributeAdapter
166
RemoteAttribute
Provides an attribute that uses the jQuery validation plug-in remote validator. Provides an adapter for the RequiredAttributeAttribute attribute. Represents an attribute that forces an unsecured HTTP request to be re-sent over HTTPS. Provides the context for the OnResultExecuted method of the ActionFilterAttribute class. Provides the context for the OnResultExecuting method of the ActionFilterAttribute class. Extends a RouteCollection object for MVC routing. Represents a value provider for route data that is contained in an object that implements the IDictionary(Of TKey, TValue) interface. Represents a factory for creating route-data value provider objects. Represents a list that lets users select one item. Represents the selected item in an instance of the SelectList class. Specifies the session state of the controller. Provides session-state data to the current TempDataDictionary object. Provides an adapter for the StringLengthAttribute attribute. Represents a set of data that persists only from one request to the next. Encapsulates information about the current template context. Contains methods to build URLs for ASP.NET MVC within an application. Represents an optional parameter that is used by the MvcHandler class during routing.
RequiredAttributeAdapter
RequireHttpsAttribute
ResultExecutedContext
ResultExecutingContext
RouteCollectionExtensions RouteDataValueProvider
RouteDataValueProviderFactory
SelectList SelectListItem
SessionStateAttribute SessionStateTempDataProvider
StringLengthAttributeAdapter TempDataDictionary
TemplateInfo UrlHelper
UrlParameter
167
ValidatableObjectAdapter ValidateAntiForgeryTokenAttribute
Provides an object adapter that can be validated. Represents an attribute that is used to prevent forgery of a request. Represents an attribute that is used to mark action methods whose input must be validated. Represents the collection of value-provider objects for the application. Obsolete. Represents a dictionary of value providers for the application. Represents a container for value-provider factory objects. Represents a factory for creating value-provider objects. Represents the collection of value-provider factories for the application. Represents the result of binding a value (such as from a form post or query string) to an action-method argument property, or to the argument itself. Encapsulates information that is related to rendering a view. Represents a container that is used to pass data between a controller and a view. Represents a container that is used to pass strongly typed data between a controller and a view. Encapsulates information about the current template content that is used to develop templates and about HTML helpers that interact with templates. Represents a collection of view engines that are available to the application. Represents the result of locating a view engine. Represents a collection of view engines that are available to the application. Represents the information that is needed to build a master
ValidateInputAttribute
ValueProviderCollection
ValueProviderDictionary
ValueProviderResult
ViewContext ViewDataDictionary
ViewDataDictionary(Of TModel)
ViewDataInfo
ViewEngineCollection
ViewEngineResult ViewEngines
ViewMasterPage
168
view page. ViewMasterPage(Of TModel) Represents the information that is required in order to build a strongly typed master view page. Represents the properties and methods that are needed to render a view as a Web Forms page. Represents the information that is required in order to render a strongly typed view as a Web Forms page. Represents a class that is used to render a view by using an IView instance that is returned by an IViewEngine object. Represents a base class that is used to provide the model to the view and then render the view to the response. Provides an abstract class that can be used to implement a view start (master) page. Provides a container for TemplateInfo objects. Provides a container for TemplateInfo objects. Represents the type of a view. Represents the information that is needed to build a user control. Represents the information that is required in order to build a strongly typed user control. Represents an abstract base-class implementation of the IViewEngine interface. Represents the information that is needed to build a Web Forms page in ASP.NET MVC. Represents a view engine that is used to render a Web Forms page to the response. Represents the properties and methods that are needed in order to render a view that uses ASP.NET Razor syntax. Represents the properties and methods that are needed in order to render a view that uses ASP.NET Razor syntax.
ViewPage
ViewPage(Of TModel)
ViewResult
ViewResultBase
ViewStartPage
ViewUserControl(Of TModel)
VirtualPathProviderViewEngine
WebFormView
WebFormViewEngine
WebViewPage
WebViewPage(Of TModel)
169
Interfaces
Interface IActionFilter IActionInvoker Description Defines the methods that are used in an action filter. Defines the contract for an action invoker, which is used to invoke an action in response to an HTTP request. Defines the methods that are required for an authorization filter. Provides a way for the ASP.NET MVC validation framework to discover at run time whether a validator has support for client validation. Defines the methods that are required for a controller. Provides fine-grained control over how controllers are instantiated using dependency injection. Defines the methods that are required for a controller factory. Defines the methods that simplify service location and dependency resolution. Defines the methods that are required for an exception filter. Provides an interface for finding filters. Provides an interface for exposing attributes to the AssociatedMetadataProvider class. Defines the methods that are required for a model binder. Defines methods that enable dynamic implementations of model binding for classes that implement the IModelBinder interface. Defines members that specify the order of filters and whether multiple filters are allowed. Defines the methods that are required for a result filter. Associates a route with an area in an ASP.NET MVC application. Defines the contract for temporary-data providers that store data that is
IAuthorizationFilter IClientValidatable
IController IControllerActivator
IControllerFactory IDependencyResolver
IModelBinder IModelBinderProvider
IMvcFilter
170
viewed on the next request. IUnvalidatedValueProvider Represents an IValueProvider interface that can skip request validation. IValueProvider IView IViewDataContainer IViewEngine IViewLocationCache Defines the methods that are required for a value provider in ASP.NET MVC. Defines the methods that are required for a view. Defines the methods that are required for a view data dictionary. Defines the methods that are required for a view engine. Defines the methods that are required in order to cache view locations in memory. Provides fine-grained control
IViewPageActivator
171
Create a web site Add files and folders Add a consistent look Add navigation Add a database
A web server markup language (Razor using VB or C#) A web server (IIS Express) A database server (SQL Server Compact) ASP.NET web controls and web components A full web development framework (ASP.NET)
You should install Visual Web Developer, to get the full benefits from this demo. If you want to install Visual Web Developer, click on this picture:
172
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.
173
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 likec:\w3schools_demo\DemoWF before clicking OK.
174
What We Will Do
In this chapter we will:
a new empty web site the necessary folders a standard style sheet for the site a standard layout for the site a home page for the site
Start Visual Web Developer Click on "New Web Site..." Choose "Visual Basic (or Visual C#) Select the template "ASP.NET Empty Web Site" Set the file location to something like c:\w3schools_demo\DemoWF
2. Create 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
175
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; }
176
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).
177
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.
178
.css
.js
.aspx
.ascx
.asax
.asmx
.cs
.vb
.config
.master
179
What We Will Do
In this chapter we will:
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.
180
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.aspx">Home</a></li> <li><a href="About.aspx">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; } h2 {
181
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).
182
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.
183
What We Will Do
In this chapter we will:
Create a database Add data to the database Create a page to list the database
Right-click the App_Data folder in the Solution Explorer window Select Add, New Item Select SQL Server Compact Local Database * Name the database Movies.sdf. Click the Add button
* If SQL Server Compact Local Database is not an option, you have not installed SQL Server Compact on your computer. Install it from this link: SQL Server Compact Visual Web Developer automatically creates the database in the App_Data folder. Note: In this tutorial it is expected that you have some knowledge about SQL databases. If you want to study this topic first, please visit our SQL Tutorial.
184
Allow Nulls No No No No
Columns explained: ID is an integer (whole number) used to identify each record in the table. Title is a 100 character text column to store the name of the movie. Director is a 100 character text column to store the director's name. Date is a datetime column to store the release date of the movie. After creating the columns described above, you must make the ID column the table's primary key (record identifier). To do this, click on the column name (ID) and select Primary Key. Also, in theColumn Properties window, set the Identity property to True:
185
When you have finished creating the table columns, save the table and name it Movies.
186
ID 1 2
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>
DataField="ID" HeaderText="ID" /> DataField="Title" HeaderText="Title" /> DataField="Director" HeaderText="Director" /> DataField="Date" HeaderText="Date" />
187
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.
188
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
189
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.
A web server markup language (Razor using VB or C#) A web server (IIS Express) A database server (SQL Server Compact) ASP.NET web controls and web components A full web development framework (ASP.NET)
You should install Visual Web Developer, to get the full benefits from this tutorial. If you want to install VWD, go to the chapter ASP.NET Web Forms Demo.
ASP.NET References
At the end of this tutorial you will find a complete ASP.NET reference with objects, components, properties and methods. ASP.NET Reference
190
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!
191
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.
192
<html> <body bgcolor="yellow"> <center> <h2>Hello W3Schools!</h2> <p><%Response.Write(now())%></p> </center> </body> </html>
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
193
194
<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.
HTML Server Controls - Traditional HTML tags Web Server Controls - New ASP.NET tags Validation Server Controls - For input validation
195
<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.
196
In the following example we declare a Button server control in an .aspx file. Then we create an event handler for the Click event which changes the text on the button:
<script runat="server"> Sub submit(Source As Object, e As EventArgs) button1.Text="You clicked me!" End Sub </script> <html> <body> <form runat="server"> <asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit"/> </form> </body> </html>
197
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
198
<% 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>
199
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.
200
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:
201
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" /> .....some code </form>
Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control. Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submit button, the form value will disappear:
Example
<html> <body> <form action="demo_classicasp.aspx" method="post"> Your name: <input type="text" name="fname" size="20"> <input type="submit" value="Submit"> </form> <% dim fname fname=Request.Form("fname") If fname<>"" Then Response.Write("Hello " & fname & "!")
202
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" />
203
<asp:Button OnClick="submit" Text="Submit" runat="server" /> <p><asp:Label id="lbl1" runat="server" /></p> </form> </body> </html>
Show example
204
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>
205
</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">
206
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 End Sub </script> <html> <body> <form runat="server"> Enter your name:
207
<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
208
<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:
209
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
210
Data Binding
The following controls are list controls which support data binding:
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.
211
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")
212
<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>
asp:RadioButtonList
213
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
214
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.
215
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>
216
Data Binding
A Hashtable object may automatically generate the text and values to the following controls:
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>
217
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
<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
218
Note: You cannot choose the sort order of the items added to the Hashtable. To sort items alphabetically or numerically, use the SortedList object.
219
<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>
220
Data Binding
A SortedList object may automatically generate the text and values to the following controls:
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>
221
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
<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
222
223
An XML File
Here is an XML file named "countries.xml":
<?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country> <text>Norway</text> <value>N</value> </country> <country> <text>Sweden</text> <value>S</value> </country> <country> <text>France</text> <value>F</value> </country> <country> <text>Italy</text> <value>I</value> </country> </countries>
Take a look at the XML file: countries.xml
224
<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:
<%@ 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 </script> <html> <body>
225
<form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> </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
<%@ 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
226
227
<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year> </cd> <cd> <title>Still got the blues</title> <artist>Gary Moore</artist> <country>UK</country> <company>Virgin records</company>
228
<price>10.20</price> <year>1990</year> </cd> <cd> <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year> </cd> </catalog>
Take a look at the XML file: cdcatalog.xml First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspx page:
<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> <ItemTemplate> ... </ItemTemplate>
229
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>
230
<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
231
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>
232
<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
233
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>
234
<tr> <td colspan="6"><hr /></td> </tr> </SeparatorTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </form> </body> </html>
Show example
235
<?xml version="1.0" encoding="ISO-8859-1"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year> </cd> <cd> <title>Still got the blues</title> <artist>Gary Moore</artist>
236
<country>UK</country> <company>Virgin records</company> <price>10.20</price> <year>1990</year> </cd> <cd> <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year> </cd> </catalog>
Take a look at the XML file: cdcatalog.xml First, import the "System.Data" namespace. We need this namespace to work with DataSet objects. Include the following directive at the top of an .aspx page:
<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> ...
237
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>
238
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
239
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 </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
240
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"
241
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
242
243
What is ADO.NET?
ADO.NET ADO.NET ADO.NET ADO.NET is a part of the .NET Framework consists of a set of classes used to handle data access is entirely based on XML has, unlike ADO, no Recordset object
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load dim dbconn dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & server.mappath("northwind.mdb")) dbconn.Open()
244
<%@ Import Namespace="System.Data.OleDb" %> <script runat="server"> sub Page_Load dim dbconn,sql,dbcomm 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) end sub </script>
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:
<%@ 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() end sub </script>
245
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>
246
Show example
dbread.Close() dbconn.Close()
247
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 contain 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.
248
249
<?xml version="1.0" encoding="ISO-8859-1" ?> <siteMap> <siteMapNode title="Home" url="/aspnet/w3home.aspx"> <siteMapNode title="Services" url="/aspnet/w3services.aspx"> <siteMapNode title="Training" url="/aspnet/w3training.aspx"/> <siteMapNode title="Support" url="/aspnet/w3support.aspx"/> </siteMapNode> </siteMapNode> </siteMap>
Rules for creating a sitemap file:
The XML file must contain a <siteMap> tag surrounding the content The <siteMap> tag can only have one <siteMapNode> child node (the "home" page) Each <siteMapNode> can have several child nodes (web pages) Each <siteMapNode> has attributes defining page title and URL
Note: The sitemap file must be placed in the root directory of the web and the URL attributes must be relative to the root directory.
250
Dynamic Menu
The <asp:Menu> control displays a standard site navigation menu. Code Example:
<asp:SiteMapDataSource id="nav1" runat="server" /> <form runat="server"> <asp:Menu runat="server" DataSourceId="nav1" /> </form>
The <asp:Menu> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap). Click here to see a demo of Menu, TreeView, and SiteMapPath
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:
<asp:SiteMapDataSource id="nav1" runat="server" /> <form runat="server"> <asp:TreeView runat="server" DataSourceId="nav1" /> </form>
The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu. The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the <asp:SiteMapDataSource> control. The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap). Click here to see a demo of Menu, TreeView, and SiteMapPath
251
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:
252
ASP.NET HTML Controls HTMLAnchor HTMLButton HTMLImage HTMLImage 2 HTMLInputbutton HTMLInputCheckbox HTMLInputHidden HTMLInputImage HTMLInputRadiobutton HTMLTable HTMLTable 2 HTMLTextarea ASP.NET Web Controls AdRotator Button Button 2 Calendar Calendar 2 Calendar 3 Checkbox CheckboxList DataList DataList with styles DataList with <AlternatingItemTemplate> DropdownList Hyperlink Image ImageButton Label LinkButton Listbox Literal Literal 2 Panel Radiobutton RadiobuttonList Repeater Repeater with <AlternatingItemTemplate> Repeater with <SeparatorTemplate> Table Table 2 Textbox Textbox 2 Textbox 3 XML
253
ASP.NET Validation Controls CompareValidator CompareValidator 2 CustomValidator RangeValidator RangeValidator 2 RegularExpressionValidator RequiredFieldValidator Validationsummary Validationsummary 2 ASP.NET Events Page_Load Page.IsPostBack ASP.NET Data Binding ArrayList RadioButtonList ArrayList DropDownList Hashtable RadioButtonList 1 Hashtable RadiobuttonList 2 Hashtable DropDownList SortedList RadioButtonList 1 SortedList RadiobuttonList 2 SortedList DropDownList XML RadiobuttonList ASP.NET Database Database connection - Bind to a Repeater control Database connection - Bind to a DataList control
254