ASP.NET Web Pages – Tutorial

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – Tutorial
❮ Previous Next ❯
Easy Learning with “Run Example”
Our “Run Example” tool 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 Pages

    

The time is @DateTime.Now

Run Example »
ASP.NET Web Pages
Web Pages is one of many programming models for creating ASP.NET web sites and web applications.

Web Pages provides an easy way to combine HTML, CSS, and server code:

Easy to learn, understand, and use
Uses an SPA application model (Single Page Application)
Similar to PHP and Classic ASP
VB (Visual Basic) or C# (C sharp) scripting languages
In addition, Web Pages applications are easily extendable with programmable helpers for databases, videos, graphics, social networking and more.

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

In this Web Pages tutorial you will learn how to combine HTML, CSS, JavaScript and server code, using server code written in VB 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 Omegas 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 markup with VB or C# code)
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.

Download WebMatrix from this link: WebMatrix

❮ Previous Next ❯

ASP and ASP.NET Tutorials

Toggle navigation
TUTORIAL HOME
ASP and ASP.NET Tutorials
❮ Home Next ❯
ASP stands for Active Server Pages

ASP is a development framework for building web pages.

ASP supports many different development models:

Classic ASP
ASP.NET Web Forms
ASP.NET MVC
ASP.NET Web Pages
ASP.NET API
ASP.NET Core
The ASP Technology
ASP and ASP.NET are server side technologies.

Both technologies enable computer code to be executed by an Internet server.

When a browser requests an ASP or ASP.NET file, the ASP engine reads the file, executes any code in the file, and returns the result to the browser.

Classic ASP – Active Server Pages
ASP (aka Classic ASP) was introduced in 1998 as Microsoft’s first server side scripting language.

Classic ASP pages have the file extension .html and are normally written in VBScript.

Visit our Classic ASP Tutorial »
ASP.NET
ASP.NET was released in 2002 as a successor to Classic ASP.

ASP.NET pages have the extension .htmlx  and are normally written in C# (C sharp).

ASP.NET 4.6 is the latest official version of ASP.NET.

ASP.NET 5 was expected to be an important redesign of ASP.NET.

However, the development of ASP.NET 5 was stopped in favor of ASP.NET Core.

ASP.NET Web Pages
ASP.NET Web Pages is an SPA application model (Single Page Application).

The SPA model is quite similar to PHP and Classic ASP.

ASP.NET Web Pages is being merged into the new ASP.NET Core.

Visit our Web Pages Tutorial »
ASP.NET MVC
ASP.NET MVC is an MVC application model (Model-View-Controller).

ASP.NET MVC is being merged into the new ASP.NET Core.

ASP.NET MVC is not covered in this tutorial.

ASP.NET Web API
ASP.NET API is an API application model (Application Programming Interface).

ASP.NET API is being merged into the new ASP.NET Core.

ASP.NET API is not covered in this tutorial.

ASP.NET Web Forms
ASP.NET Web Forms is an event driven application model.

ASP.NET Web Forms is not a part of the new ASP.NET Core.

ASP.NET Web Forms is not covered in this tutorial.

ASP.NET Core
ASP.NET Core was released in 2016.

ASP.NET Core merges ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages into one application framework.

ASP.NET Core is not covered in this tutorial.

❮ Home Next ❯

ASP.NET Web Pages – Page Layout

TUTORIAL HOME
ASP.NET Web Pages – Page Layout
❮ Previous Next ❯
With Web Pages it is easy to create a web site with a consistent layout.

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

Every page have the same header
Every page have the same footer
Every page have the same style and layout
With Web Pages this can be done very efficiently. You can have reusable blocks of content (content blocks), like headers and footers, in separate files.

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

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

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

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

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

This is how it looks in code:

Example

@RenderPage(“header.cshtml”)

Hello Web Pages

This is a paragraph

@RenderPage(“footer.cshtml”)

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 Omegas. All rights reserved.

Any Web Page:
@{Layout=”Layout.cshtml”;}

Welcome to Omegas

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.

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 = “username@example.com“;
WebMail.Password = “your-password”;
WebMail.From = “your-name-here@example.com“;
}

❮ Previous Next ❯

ASP.NET Web Pages – Folders

TUTORIAL HOME
ASP.NET Web Pages – Folders
❮ Previous Next ❯
This 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 site:

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: https://www.Omegas.com/html/html5_intro.html

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

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.

URL https://www.Omegas.com/html/html5_intro.html
Server name Omegas
Virtual path /html/html5_intro.html
Physical path C:\MyWebSites\Omegas\html\html5_intro.html
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.

❮ Previous Next ❯

ASP.NET Web Pages – Adding Razor Code

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – Adding Razor Code
❮ Previous Next ❯
ASP.NET Web Pages use Razor markup with C# or VB code

Razor Markup
Razor is a simple markup syntax for embedding server code (C# or VB) into ASP.NET web pages.

Example

    
     Web Pages Demo

    

Hello Web Pages

    

The time is @DateTime.Now

The page above contains both ordinary HTML markup and Razor markup.

Razor Syntax for C#
C# code blocks are enclosed in @{ … }
Inline expressions (variables or 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

Razor Syntax for VB
VB code blocks are enclosed in @Code … End Code
Inline expressions (variables or 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
VB Example

@Code dim myMessage = “Hello World” End Code

The value of myMessage is: @myMessage


@Code
dim greeting = “Welcome to our site!”
dim weekDay = DateTime.Now.DayOfWeek
dim greetingMessage = greeting & ” Today is: ” & weekDay
End Code

The greeting is: @greetingMessage

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.

❮ Previous Next ❯

ASP.NET Web Pages – Global Pages

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – Global Pages
❮ Previous Next ❯
This 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.

❮ Previous Next ❯

ASP.NET Web Pages – HTML Forms

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – HTML Forms
❮ Previous Next ❯
A form is a section of an HTML document where you put input controls (text boxes, check boxes, radio buttons, and pull-down lists)

Creating an HTML Input Page
Razor Example

@{
if (IsPost) {
string companyname = Request[“CompanyName”];
string contactname = Request[“ContactName”];

You entered:

Company Name: @companyname

Contact Name: @contactname

}
else
{

Company Name:

Contact Name:

}
}

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:

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

Razor Example
@{
var imagePath=””;
if (Request[“Choice”] != null)
   {imagePath=”images/” + Request[“Choice”];}
}

Display Images

I want to see:

  Photo 1
  Photo 2
  Photo 3

@if (imagePath != “”)
{

Sample

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.

❮ Previous Next ❯

ASP.NET Web Pages – Files

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – Files
❮ Previous Next ❯
This 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,Lucas
Steven,Spielberg
Alfred,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  }
 

}

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

❮ Previous Next ❯

ASP.NET Web Pages – Objects

Toggle navigation
TUTORIAL HOME
ASP.NET Web Pages – Objects
❮ Previous Next ❯
Web 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
Method Description
href Builds a URL using the specified parameters
RenderBody() Renders the portion of a content page that is not within a named section (In layout pages)
RenderPage(page) Renders the content of one page within another page
RenderSection(section) Renders the content of a named section (In layout pages)
Write(object) Writes the object as an HTML-encoded string
WriteLiteral Writes an object without HTML-encoding it first.
Some Page Object Properties
Property Description
IsPost Returns true if the HTTP data transfer method used by the client is a POST request
Layout Gets or sets the path of a layout page
Page Provides property-like access to data shared between pages and layout pages
Request Gets the HttpRequest object for the current HTTP request
Server Gets the HttpServerUtility object that provides web-page processing methods
The Page Property (of the Page Object)
The Page property of the Page Object, provides property-like access to data shared between pages and layout pages.

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

Page.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 Omegas

Web Site Main Ingredients

A Home Page (Default.cshtml)

A Layout File (Layout.cshtml)

A Style Sheet (Site.css)

Layout.cshtml

@Page.Title

@RenderBody()

❮ Previous Next ❯

ASP.NET Web Pages – Helpers

TUTORIAL HOME
ASP.NET Web Pages – Helpers
❮ Previous Next ❯
Web Helpers greatly simplifies web development and common programming tasks.

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

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

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

Below is a short description of some useful Razor helpers:

The 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.

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.

Analytics (Google)
Helper Description
Analytics.GetGoogleHtml(webPropertyId) Renders the Google Analytics JavaScript code for the specified ID.
Analytics.GetStatCounterHtml(project, security) Renders the StatCounter Analytics JavaScript code for the specified project.
Analytics.GetYahooHtml(account) Renders the Yahoo Analytics JavaScript code for the specified account.
Bing
Helper Description
Bing.SearchBox([boxWidth]) Passes a search to Bing. To specify the site to search and a title for the search box, you can set the Bing.SiteUrl and Bing.SiteTitle properties. Normally you set these properties in the _AppStart  page.
Bing.AdvancedSearchBox([, boxWidth] [, resultWidth] [, resultHeight]
  [, themeColor] [, locale]) Displays Bing search results in the page with optional formatting. To specify the site to search and a title for the search box, you can set the Bing.SiteUrl and Bing.SiteTitle properties. Normally you set these properties in the _AppStart  page.
Crypto
Helper Description
Crypto.Hash(string [, algorithm])
Crypto.Hash(bytes [, algorithm]) Returns a hash for the specified data. The default algorithm is sha256.
Facebook
Helper Description
Facebook.LikeButton(href [, buttonLayout] [, showFaces] [, width] [, height]
[, action] [, font] [, colorScheme] [, refLabel]) Lets Facebook users make a connection to pages.
FileUpload
Helper Description
FileUpload.GetHtml([initialNumberOfFiles] [, allowMoreFilesToBeAdded]
  [, includeFormTag] [, addText] [, uploadText]) Renders UI for uploading files.
GamerCard
Helper Description
GamerCard.GetHtml(gamerTag) Renders the specified Xbox gamer tag.
Gravatar Object Reference
Helper Description
Gravatar.GetHtml(email [, imageSize] [, defaultImage] [, rating]
  [, imageExtension] [, attributes]) Renders the Gravatar image for the specified email address.
Json
Helper Description
Json.Encode(object) Converts a data object to a string in the JavaScript Object Notation (JSON) format.
Json.Decode(string) Converts a JSON-encoded input string to a data object that you can iterate over or insert into a database.
LinkShare
Helper Description
LinkShare.GetHtml(pageTitle [, pageLinkBack] [, twitterUserName]
  [, additionalTweetText] [, linkSites]) Renders social networking links using the specified title and optional URL.
ModelState
Helper Description
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.
ObjectInfo
Helper Description
ObjectInfo.Print(value [, depth] [, enumerationLength]) Renders the properties and values of an object and any child objects.
Recaptcha
Helper Description
Recaptcha.GetHtml([, publicKey] [, theme] [, language] [, tabIndex]) Renders the reCAPTCHA verification test.
ReCaptcha.PublicKey
ReCaptcha.PrivateKey Sets public and private keys for the reCAPTCHA service. Normally you set these properties in the _AppStart page.
ReCaptcha.Validate([, privateKey]) Returns the result of the reCAPTCHA test.
ServerInfo
Helper Description
ServerInfo.GetHtml() Renders status information about ASP.NET Web Pages.
Twitter
Helper Description
Twitter.Profile(twitterUserName) Renders a Twitter stream for the specified user.
Twitter.Search(searchQuery) Renders a Twitter stream for the specified search text.
Video
Helper Description
Video.Flash(filename [, width, height]) Renders a Flash video player for the specified file with optional width and height.
Video.MediaPlayer(filename [, width, height]) Renders a Windows Media player for the specified file with optional width and height.
Video.Silverlight(filename, width, height) Renders a Silverlight player for the specified .xap file with required width and height.
WebCache
Helper Description
WebCache.Get(key) Returns the object specified by key, or null if the object is not found.
WebCache.Remove(key) Removes the object specified by key from the cache.
WebCache.Set(key, value [, minutesToCache] [, slidingExpiration]) Puts value into the cache under the name specified by key.
WebImage
Helper Description
WebImage(path) Loads an image from the specified path.
WebImage.AddImagesWatermark(image) Adds the specified image as a watermark.
WebImage.AddTextWatermark(text) Adds the specified text to the image.
WebImage.FlipHorizontal()
WebImage.FlipVertical() Flips the image horizontally or vertically.
WebImage.GetImageFromRequest() Loads an image when an image is posted to a page during a file upload.
WebImage.Resize(width, height) Resizes the image.
WebImage.RotateLeft()
WebImage.RotateRight() Rotates the image to the left or the right.
WebImage.Save(path [, imageFormat]) Saves the image to the specified path.

❮ Previous Next ❯