Mvc tutorial

139
ASP.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 MVC Model View Controller Web Forms Event Driven 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 separates web applications into 3 different components: Models for data Views for display Controllers for input The traditional ASP.NET event driven development model: Web pages with added server controls, server events, and server code. Web Pages Tutorial If you are new to ASP.NET, Web Pages is the perfect place to start. Web Pages is the easiest development model for developing ASP.NET web sites. In our Web Pages tutorial you will learn how to combine HTML, CSS, JavaScript and server code, using the latest Razor server markup syntax with Visual Basic or C#. You will also learn how to extend your web pages with programmable Web Helpers, including database, video, graphics, social networking and much more. Start learning ASP.NET Web Pages now! 1

description

mvc tutorial

Transcript of Mvc tutorial

ASP.NET TutorialASP.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 PagesSingle Pages Model MVCModel View Controller Web FormsEvent Driven 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 separates web applications into 3 different components:

Models for dataViews for displayControllers for inputThe traditional ASP.NET event driven development model:

Web pages with added server controls, server events, and server code.

Web Pages Tutorial

If you are new to ASP.NET, Web Pages is the perfect place to start. Web Pages is the easiest development model for developing ASP.NET web sites.

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

You will also learn how to extend your web pages with programmable Web Helpers, including database, video, graphics, social networking and much more.

Start learning ASP.NET Web Pages now!

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.

Start learning ASP.NET MVC now!

Web Forms Tutorial

Web Forms is the traditional ASP.NET model, based on event driven Web Forms and post backs.

Over the years, developers have used ASP.NET Web Forms to create many of the largest websites in the world.

If you want to study the design model used by many web developers over the last 10 years, this is the place to start.Start learning ASP.NET Web Forms now!

Who Are These Tutorials For?

The tutorials above are for anyone who wants to learn to build websites on the Microsoft ASP.NET platform, from hobby-related sites, to new, modern, and fully commercial webs.

Even if you are new to web programming, you should be able to follow the tutorials, but it will help if you have a basic understanding of HTML and CSS.

It will also help if you have a basic understanding of scripting languages like JavaScript or VB (Visual Basic).

Do you have a preference for VB over C#? Do you want to learn both languages? The good news are: In the W3Schools tutorials most code examples are in both languages.

If you are a professional web developer with prior ASP.NET experience, you can still learn a lot, since these tutorials covers a lot of new ASP.NET concepts, 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, visit our Classic ASP Tutorial.

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.

ASP.NET Programming Languages

This tutorial covers the following programming languages:

Visual Basic (VB.NET)

C# (Pronounced C sharp)

ASP.NET Server Technologies

This tutorial covers the following server technologies:

Web Pages (with Razor syntax)

MVC (Model View Controller)

Web Forms (traditional ASP.NET)

ASP.NET Development Tools

ASP.NET supports the following development tools:

WebMatrix

Visual Web Developer

Visual Studio

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

ASP.NET File Extensions

Classic ASP files have the file extension .asp

ASP.NET files have the file extension .aspx

ASP.NET files with Razor C# syntax have the file extension .cshtml

ASP.NET files with Razor VB syntax have the file extension .vbhtml

ASP.NET Web Pages - TutorialASP.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.

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 example, follow the ASP.NET Web Pages Demo.

Easy Learning with "Run Example"

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

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

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

Web Pages Example

Hello Web PagesThe time is @DateTime.Now

Run Example

What is Web Pages?

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

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

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

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 is easy extendable with programmable Web Helpers, including database, video, graphics, social networking and much more.

Web Pages Tutorial

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

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

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

Web Pages Examples

Learn by examples!

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

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

Web Pages Examples

Web Pages References

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

Web Pages References

We Have Used WebMatrix

In this tutorial, we have used WebMatrix.

WebMatrix is a simple but powerful free ASP.NET development tool from Microsoft, tailor made for Web Pages.

WebMatrix contains:

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 full web development framework (ASP.NET)

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.

If you want to try WebMatrix, follow the link below to install:

http://www.microsoft.com/web/gallery/install.aspx?appid=WebMatrixASP.NET Web Pages - Adding Razor CodeIn this tutorial we will use Razor markup with C# and Visual Basic code

What is Razor?

Razor is a markup syntax for adding server-based code to web pages

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

Razor is a server side markup syntax much like ASP and PHP

Razor supports C# and Visual Basic programming languages

Adding Razor Code

Remember the web page from previous chapter:

Web Pages Demo

Hello Web Pages

Now add some Razor code to the example:

Example

Web Pages Demo

Hello Web Pages The time is @DateTime.Now

Run example

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

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

Main Razor Syntax Rules for C#

Razor code blocks are enclosed in @{ ... }

Inline expressions (variables and functions) start with @

Code statements end with semicolon

Variables are declared with the var keyword

Strings are enclosed with quotation marks

C# code is case sensitive

C# files have the extension .cshtml

C# Example

@{ var myMessage = "Hello World"; }

The value of myMessage is: @myMessage

@{var greeting = "Welcome to our site!";var weekDay = DateTime.Now.DayOfWeek;var greetingMessage = greeting + " Today is: " + weekDay;}The greeting is: @greetingMessage

Run example

Main Razor Syntax Rules for VB

Razor code blocks are enclosed in @Code ... End Code

Inline expressions (variables and functions) start with @

Variables are declared with the Dim keyword

Strings are enclosed with quotation marks

VB code is not case sensitive

VB files have the extension .vbhtml

Example

@Code dim myMessage = "Hello World" End CodeThe value of myMessage is: @myMessage@Codedim greeting = "Welcome to our site!"dim weekDay = DateTime.Now.DayOfWeekdim greetingMessage = greeting & " Today is: " & weekDayEnd Code

The greeting is: @greetingMessage

Run example

More About C# and Visual Basic

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

ASP.NET Web Pages - Page LayoutWith Web Pages it is easy to create a web site with a consistent layout.

A Consistent Look

On the Internet you will discover many web sites with a consistent look and feel:

Every page have the same header

Every page have the same footer

Every page have the same style and layout

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

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

Content Blocks

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

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

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

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

This is how it looks in code:

Example

@RenderPage("header.cshtml")Hello Web Pages This is a paragraph@RenderPage("footer.cshtml")

Run example

Using a Layout Page

In the previous section, you saw that including the same content in many web pages is easy.

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

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

Each content page must start with a Layout directive.

This is how it looks in code:

Layout Page:

This is header text@RenderBody() 2014 W3Schools. All rights reserved.

Any Web Page:

@{Layout="Layout.cshtml";}

Welcome to W3Schools

Lorem ipsum dolor sit amet, consectetur adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laborisnisi ut aliquip ex ea commodo consequat.

Run example

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

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

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

Preventing Files from Being Browsed

With ASP.NET, files with a name that starts with an underscore cannot be browsed from the web.

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

_header.cshtml

_footer.cshtml

_Layout.cshtml

Hiding Sensitive Information

With ASP.NET, the common way to hide sensitive information (database passwords, email passwords, etc.) is to keep the information in a separate file named "_AppStart".

_AppStart.cshtml

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

ASP.NET Web Pages - FoldersThis chapter is about folders and folder paths.

In this chapter you will learn:

About Logical and Physical folder structures

About Virtual and Physical names

About web URLs and Paths

Logical Folder Structure

Below is a typical folder structure for an ASP.NET web pages web:

The "Account" folder contains logon and security files

The "App_Data" folder contains databases and data files

The "Images" folder contains images

The "Scripts" folder contains browser scripts

The "Shared" folder contains common files (like layout and style files)

Physical Folder Structure

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

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

Virtual and Physical Names

From the example above:

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

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

URLs and Paths

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

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

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

URLhttp://www.w3schools.com/html/html5_intro.asp

Server namew3schools

Virtual path/html/html5_intro.asp

Physical pathC:\MyWebSites\w3schools\html\html5_intro.asp

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

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

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

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

The ~ Operator

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

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

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

The Server.MapPath Method

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

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

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

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

The Href Method

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

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

You will often use this method in HTML , , and elements:

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

The Href method is a method of the WebPage Object.

ASP.NET Web Pages - Global PagesThis chapter is about the global pages AppStart and PageStart.

Before Web Startup: _AppStart

Most server side code are written inside individual web pages. For example, if a web page contains an input form, the web page typically contains server code for reading the data.

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

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

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

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

Before Every Page: _PageStart

Just like _AppStart runs before your site starts, you can write code that runs before any page in each folder.

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

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

How Does it Work?

The following diagram shows how it works:

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

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

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

ASP.NET Web Pages - HTML FormsA form is a section of an HTML document where you put input controls (text boxes, check boxes, radio buttons, and pull-down lists)

Creating an HTML Input Page

Razor Example

@{if (IsPost) {string companyname = Request["CompanyName"];string contactname = Request["ContactName"];You entered:
Company Name: @companyname
Contact Name: @contactname }else{

Company Name:

Contact Name:


}}

Run example

Razor Example - Displaying Images

Suppose you have 3 images in your image folder, and you want to display images dynamically by the users choice.

This is easily done by a little Razor code.

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

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

Razor Example

@{var imagePath=""; if (Request["Choice"] != null) {imagePath="images/" + Request["Choice"];} } Display Images I want to see: Photo 1 Photo 2 Photo 3 @if (imagePath != ""){

}

Run example

Example explained

The server creates a variable called imagePath.

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

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

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

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

ASP.NET Web Pages - ObjectsWeb Pages is much often about Objects.

The Page Object

You have already seen some Page Object methods in use:

@RenderPage("header.cshtml")

@RenderBody()

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

If (IsPost) {

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

Some Page Object Methods

MethodDescription

hrefBuilds a URL using the specified parameters

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

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

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

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

WriteLiteralWrites an object without HTML-encoding it first.

Some Page Object Properties

PropertyDescription

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

LayoutGets or sets the path of a layout page

PageProvides property-like access to data shared between pages and layout pages

RequestGets the HttpRequest object for the current HTTP request

ServerGets the HttpServerUtility object that provides web-page processing methods

The Page Property (of the Page Object)

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

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

Page.Title

Page.Version

Page.anythingyoulike

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

Home.cshtml

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

Welcome to W3Schools

Web Site Main Ingredients

A Home Page (Default.cshtml)A Layout File (Layout.cshtml)A Style Sheet (Site.css)

Layout.cshtml

@Page.Title

@RenderBody()

ASP.NET Web Pages - FilesThis chapter is about working with text files.

Working with Text Files

Sometimes you will want to access data stored in text files.

Text files used to store data is often called flat files.

Common flat file formats are .txt, .xml, and .csv (comma-delimited values).

In this chapter you will learn: How to read and display data from a text file

Add a Text File Manually

In the example to follow, you will need a text file to work with.

On your web site, if you don't have an App_Data folder, create one.

In the App_Data folder, create a new file named Persons.txt.

Add the following content to the file:

Persons.txt

George,LucasSteven,SpielbergAlfred,Hitchcock

Displaying Data from a Text File

The example below shows how to display data from a text file:

Example

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

Reading Data from a File@foreach (string dataLine in userData) { foreach (string dataItem in dataLine.Split(',')) {@dataItem }
}

Run example

Example explained

Server.MapPath finds the exact text file path.

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

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

Displaying Data from an Excel File

With Microsoft Excel, you can save a spreadsheet as a comma separated text file (.csv file). When you do so, each row in the spreadsheet is saved as a text line, and each data column is separated by a comma.

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

ASP.NET Web Pages - DatabasesThis chapter is about working with databases.

What We Will Do

In this chapter we will:

Create a web page to list data from a database

Displaying Data from Database

With Web Pages, you can easily display data from a database.

You can connect to an existing database, or create a new database from scratch.

In this example we will connect to an existing SQL Server Compact database.

If you want to learn how to create a database for your web, please go to the chapter Web Database.

Adding a Customers Page

In the "DemoWebPages" folder, create a new CSHTML file named "Products.cshtml".

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

Products.cshtml

@{var db = Database.Open("SmallBakery");var selectQueryString = "SELECT * FROM Product ORDER BY Name";}Small Bakery Products

IdProductDescriptionPrice

@foreach(var row in db.Query(selectQueryString)){@[email protected]@[email protected]}

Run example

Example Explained

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.

(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)

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.

ASP.NET Web Pages - HelpersWeb Helpers greatly simplifies web development and common programming tasks.

ASP.NET Helpers

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

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

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

Below is a short description of some useful Razor helpers:

The WebGrid Helper

The WebGrid helper simplifies the way to display data:

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

The Chart Helper

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

INCLUDEPICTURE "http://www.w3schools.com/aspnet/07.jpg" \* MERGEFORMATINET The Chart helper can display data from arrays , from databases, or from files.

The WebMail Helper

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

The WebImage Helper

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

Keywords: flip, rotate, resize, watermark.

Third Party Helpers

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

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. In WebMatrix, open the Site workspace.

2. Click on Web Pages Administration.

3. Login to Web Pages Administration using a password *.

4. Search for helpers using the search field.

5. Click install to install your desired helpers.

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

ASP.NET Web Pages - The WebGrid HelperWebGrid - One of many useful ASP.NET Web Helpers.

Doing the HTML Yourself

In a previous chapter, you displayed database data by using razor code, and doing the HTML markup yourself:

Database Example

@{var db = Database.Open("SmallBakery");var selectQueryString = "SELECT * FROM Product ORDER BY Name";}Small Bakery Products

IdProductDescriptionPrice

@foreach(var row in db.Query(selectQueryString)){@[email protected]@[email protected]}

Run example

Using The WebGrid Helper

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

The WebGrid helper:

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 Name";var data = db.Query(selectQueryString);var grid = new WebGrid(data);}Displaying Data Using the WebGrid HelperSmall Bakery [email protected]()

Run example

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

The Chart Helper

In the previous chapters, you learned how to use an ASP.NET "Helper".

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

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

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

INCLUDEPICTURE "http://www.w3schools.com/aspnet/07.jpg" \* MERGEFORMATINET The data you display in a chart can be from an array, from a database, or from data in a file.

Chart From an Array

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

Example

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

Run example

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

- the AddTitle method specifies the chart title

- the AddSeries method adds data to the chart

- the chartType parameter defines the type of chart

- the xValue parameter defines x-axis names

- the yValues parameter defines the y-axis values

- the Write() method displays the chart

Chart From Database Data

You can run a database query and then use data from the results to create a chart:

Example

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

Run example

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

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

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

- the AddTitle method specifies the chart title

- the DataBindTable method binds the data source to the chart

- the Write() method displays the chart

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

Example

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

Run example

Chart From XML Data

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

Example

@using System.Data;

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

Run example

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

The WebMail Helper

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

Scenario: Email Support

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

First: Edit Your AppStart Page

If you have built the Demo application in this tutorial, you already have a page called _AppStart.cshtml with the following content:

_AppStart.cshtml

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

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

_AppStart.cshtml

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

Properties explained:

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

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

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

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

Password: The password of the SMTP email account.

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

Second: Create an Email Input Page

Then create an input page, and name it Email_Input:

Email_Input.cshtml

Request for Assistance

Username: