Welcome

Welcome to CMS n Web. Learn & Study completely Free Articles\Training about Web Designing\Development and CMS.

Search This Web

Tuesday, February 26, 2013

Introducing ASP.NET Web Pages 2 - Getting Started

This set of tutorials gives you an overview of ASP.NET Web Pages (version 2) and Razor syntax, a lightweight framework for creating dynamic websites. It also introduces WebMatrix, a tool for creating pages and sites.
Level: New to ASP.NET Web Pages.
Skills assumed: HTML, basic cascading style sheets (CSS).
Prerequisites: Windows XP SP3 or later. (See "What Do You Need?" later for more details.)
DownloadsCompleted website for the ASP.NET Web Pages introductory tutorial
What you'll learn in the first tutorial of the set:
  • What ASP.NET Web Pages technology is and what it's for.
  • What WebMatrix is.
  • How to install everything.
  • How to create a website by using WebMatrix.
Features/technologies discussed:
  • Microsoft Web Platform Installer.
  • WebMatrix.
  • .cshtml pages
Note   This tutorial is based on ASP.NET Web Pages version 2 and Microsoft WebMatrix 2.

What Should You Know?

We're assuming that you're familiar with:
  • HTML. No in-depth expertise is required. We won't explain HTML, but we also don't use anything complex. We'll provide links to HTML tutorials where we think they're useful.
  • Cascading style sheets (CSS). Same as with HTML.
  • Basic database ideas. If you've used a spreadsheet for data and sorted and filtered the data, that's the level of expertise we're generally assuming for this tutorial set.
We're also assuming that you're interested in learning basic programming. ASP.NET Web Pages use a programming language called C#. You don't have to have any background in programming, just an interest in it. If you've ever written any JavaScript in a web page before, you've got plenty of background.
Note that if you are familiar with programming, you might find that this tutorial set initially moves slowly while we bring new programmers up to speed. As we get past the first few tutorials, though, there will be less basic programming to explain and things will move along at a faster clip.

What Do You Need?

Here's what you'll need:
  • A computer that is running Windows 7, Windows Vista SP2, Windows XP SP3, Windows Server 2003 SP2, Windows Server 2008, or Windows Server 2008 R2.
  • A live internet connection.
  • Administrator privileges (required for the installation process).

What Is ASP.NET Web Pages?

ASP.NET Web Pages is a framework that you can use to create dynamic web pages. A simple HTML web page is static; its content is determined by the fixed HTML markup that's in the page. Dynamic pages like those you create with ASP.NET Web Pages let you create the page content on the fly, by using code.
Dynamic pages let you do all sorts of things. You can ask a user for input by using a form and then change what the page displays or how it looks. You can take information from a user, save it in a database, and then list it later. You can send email from your site. You can interact with other services on the web (for example, a mapping service) and produce pages that integrate information from those sources.

What is WebMatrix?

WebMatrix is a tool that integrates a web page editor, a database utility, a web server for testing pages, and features for publishing your website to the Internet. WebMatrix is free, and it's easy to install and easy to use. (It also works for just plain HTML pages, as well as for other technologies like PHP.)
You don't actually have to use WebMatrix to work with ASP.NET Web Pages. You can create pages by using a text editor, for example, and test pages by using a web server that you have access to. However, WebMatrix makes it all very easy, so these tutorials will use WebMatrix throughout.

About These Tutorials

This tutorial set is an introduction to how to use ASP.NET Web Pages. There are 9 tutorials total in this introductory tutorial set. It's part of a series of tutorial sets that takes you from ASP.NET Web Pages novice to creating real, professional-looking websites. 
This first tutorial set concentrates on showing you the basics of how to work with ASP.NET Web Pages. When you're done, you can work with additional tutorial sets that pick up where this one ends and that explore Web Pages in more depth.
We deliberately go easy on the in-depth explanations. And whenever we show something, for this tutorial set we always chose the way that we think is easiest to understand. Later tutorial sets go into more depth and show you more efficient or more flexible approaches (also more fun). But those tutorials require you to understand the basics first.
The tutorial set you've just started covers these features of ASP.NET Web Pages:
  • Introduction and getting everything installed. (That's in the tutorial you're reading.)
  • The basics of ASP.NET Web Pages programming.
  • Creating a database.
  • Creating and processing a user input form.
  • Adding, updating, and deleting data in the database.
At any point you can publish (deploy) your site to a hosting provider. We'll talk about that at the end of this tutorial set and link you to a tutorial on how to do that.

What Will You Create?

This tutorial set and subsequent ones revolve around a website where you can list movies that you like. You'll be able to enter movies, edit them, and list them. Here are a couple of the pages you'll create in this tutorial set. The first one shows the movie listing page that you'll create:
Finshed Movie app showing a movie listing
And here's the page that lets you add new movie information to your site:
Finished movie app showing the Add Movie page
Subsequent tutorial sets build on this set and add more functionality, like uploading pictures, letting people log in, sending email, and integrating with social media.
Ok, let's get started.

Note   You can download a finished version of the website that's described in these tutorials.

Installing Everything

You can install everything by using the Web Platform Installer from Microsoft. In effect, you install the installer, and then use it to install everything else.
To use Web Pages, you have to be have at least Windows XP with SP3 installed, or Windows Server 2008 or later.
On the Web Pages page of the ASP.NET website, click Install WebMatrix.
ASP.NET Web site showing "Install WebMatrix" button
This button takes you to the Web Platform Installer page on the Microsoft.com site.
Page that starts the Web Platform Installer installation
If the download doesn't start automatically, click the Install Now button. Then click Run. (If you want to save the installer, click Save and then run the installer from the folder where you saved it.)
The Web Platform Installer appears, ready to install WebMatrix. Click Install.
The installation process figures out what it has to install on your computer and starts the process. Depending on what exactly has to be installed, the process can take anywhere from a few moments to several minutes.

Hello, WebMatrix

When it's done, the installation process can launch WebMatrix automatically. If it doesn't, in Windows, from theStart menu, launch Microsoft WebMatrix.
In Windows, start Microsoft WebMatrix.
Launching WebMatrix in Windows
To begin, you'll create a blank website and add a page. In a later tutorial in this set you'll play with one of the built-in website templates.
In the start window, click Templates. Templates are prebuilt files and pages for different types of websites.
WebMatrix startup screen
In the Quick Start window, select Empty Site and name the new site "WebPagesMovies".
WebMatrix Quick Start window with Empty Site template selected
Click Next.
WebMatrix creates and opens the site:
New WebPagesMovies site open in WebMatrix
At the top, there's a Quick Access Toolbar and a ribbon, like in Microsoft Office 2010. At the bottom left, you see the workspace selector where you switch between tasks (SiteFilesDatabasesReports). On the right is the content pane for the editor and for reports. And across the bottom you'll occasionally see a notification bar for messages.
You'll learn more about WebMatrix and its features as you go through these tutorials.

Creating a Web Page

To become familiar with WebMatrix and ASP.NET Web Pages, you'll create a simple page.
In the workspace selector, select the Files workspace. This workspace lets you work with files and folders. The left pane shows the file structure of your site. The ribbon changes to show file-related tasks.
File Workspace in WebMatrix
In the ribbon, click the arrow under New and then click New File.
Using the "New" command in the ribbon to create a new file
WebMatrix displays a list of file types. Select CSHTML, and in the Name box, type "HelloWorld". A CSHTML page is an ASP.NET Web Pages page.
Creating a new CSHTML page named HelloWorld.cshtml
Click OK.
WebMatrix creates the page and opens it in the editor.
The new HelloWorld page in the WebMatrix editor
As you can see, the page contains mostly ordinary HTML markup, except for a block at the top that looks like this:
@{

}
That's for adding code, as you'll see shortly.
Notice that the different parts of the page — the element names, attributes, and text, plus the block at the top — are all in different colors. This is called syntax highlighting, and it makes it easier to keep everything clear. It's one of the features that makes it easy to work with web pages in WebMatrix.

Add content for the <head> and <body> elements like in the following example. (If you want, you can just copy the following block and replace the entire existing page with this code.)
@{

}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Hello World Page</title>
    </head>
    <body>
        <h1>Hello World Page</h1>
        <p>Hello World!</p>
    </body>
</html>
In the Quick Access Toolbar or in the File menu, click Save.
Save button in WebMatrix Quick Access Toolbar

Testing the Page

In the Files workspace, right-click the HelloWorld.cshtml page and then click Launch in browser.
Running a page using the Run button in the WebMatrix ribbon
WebMatrix starts a built-in web server (IIS Express) that you can use to test pages on your computer. (Without IIS Express in WebMatrix, you'd have to publish your page to a web server somewhere before you could test it.) The page is displayed in your default browser.
"Hello World" page running in the browser

Adding Some Server-Side Code

Close the browser and go back to the page in WebMatrix.
Add a line to the code block so that it looks like the following code:
@{
   var currentDateTime = DateTime.Now;
}
This is a little bit of Razor code. It's probably clear that it gets the current date and time and puts that value into avariable named currentDateTime. You'll read more about Razor syntax in the next tutorial.
In the body of the page, after the <p>Hello World!</p> element, add the following:
<p>Right now it's @currentDateTime</p>
This code gets the value that you put into the currentDateTime variable at the top and inserts it into the markup of the page. The @ character marks the ASP.NET Web Pages code in the page.
Run the page again (WebMatrix saves the changes for you before it runs the page). This time you see the date and time in the page.
"Hello World" page running in the browser with a dynamically generated time display
Wait a few moments and then refresh the page in the browser. The date and time display is updated.
In the browser, look at the page source. It looks like the following markup:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Hello World Page</title>
    </head>
    <body>
        <h1>Hello World Page</h1>
        <p>Hello World!</p>
        <p>Right now it's 1/18/2012 2:49:50 PM</p>
    </body>
</html>
Notice that the @{ } block at the top isn't there. Also notice that the date and time display shows an actual string of characters (1/18/2012 2:49:50 PM or whatever), not @currentDateTime like you had in the .cshtml page. What happened here is that when you ran the page, ASP.NET processed all the code (very little in this case) that was marked with @. The code produces output, and that output was inserted into the page.

This Is What ASP.NET Web Pages Are About

When you read that ASP.NET Web Pages produces dynamic web content, what you've seen here is the idea. The page you just created contains the same HTML markup that you've seen before. It can also contain code that can perform all sorts of tasks. In this example, it did the trivial task of getting the current date and time. As you saw, you can intersperse code with the HTML to produce output in the page. When someone requests a .cshtml page in the browser, ASP.NET processes the page while it's still in the hands of the web server. ASP.NET inserts the output of the code (if any) into the page as HTML. When the code processing is done, ASP.NET sends the resulting page to the browser. All the browser ever gets is HTML. Here's a diagram:
Conceptual flow of how ASP.NET generates HTML dynamically
The idea is simple, but there are many interesting tasks that the code can perform, and there are many interesting ways in which you can dynamically add HTML content to the page. And ASP.NET .cshtml pages, like any HTML page, can also include code that runs in the browser itself (JavaScript and jQuery code). You'll explore all of these things in this tutorial set and in subsequent ones.

Coming Up Next

In the next tutorial in this series, you explore ASP.NET Web Pages programming a little more.

Create an ASP.NET website from scratch (web matrix)

What you'll do
  • Become familiar with the WebMatrix user interface.
  • Use a site template to create a blank site, then add files and code to customize it.
  • Get started with ASP.NET Razor syntax.
  • Install the ASP.NET Web Helpers Library 1.1 and create a dynamic web page that displays a live Twitter feed.
  • Analyze requests to your website and find errors.
  • Add a database with a table and data to your website, then use a WebGrid helper to display the data in a web page.
  • Run an analysis of your website to enhance its visibility to search engines.
  • Learn how to find web hosting and publish your site to the web.
What you'll need
To run the steps in this walkthrough, you must be running Windows XP SP3 or a later version of Windows.

Introducing WebMatrix

Seamless, simple, small, and best of all, free, WebMatrix includes a complete collection of web development tools that installs in minutes. It elegantly integrates a web server with database and programming frameworks to create a single, integrated experience.  Use WebMatrix to streamline the way you code, test, and publish your own ASP.NET or PHP website. Or start a new site using the world's most popular open source apps, like DotNetNuke, Umbraco, WordPress, or Joomla. With WebMatrix on your desktop, you're using the same powerful web server, database engine, and frameworks that will run your website on the internet, which makes the transition from development to production smooth and seamless.

Getting WebMatrix

To install WebMatrix, you can use Microsoft's Web Platform Installer (Web PI 3.0), which is a free application that makes it easy to install and configure web-related technologies. You can install the Web Platform Installer from the WebMatrix download page.
On the download page, click Install Now. At the security warnings, click Run. On the Web Platform Installer page, click Install.
image01
On the Web Platform Installation screen, WebMatrix displays a list of additional required components. Click I Accept. The install begins.
image01a

Creating Your First Website

Right out of the box, WebMatrix gives you a number of options for how to create sites. You can create a site from a template or from a folder that already contains ASP.NET web pages. Or you can download an open-source application from the gallery as the basis for your site.
image02
For this walkthrough, click Site From Template to see a list of available templates.
image03
Select the Empty Site template to create a new site from scratch, and name it WebMatrixDemo. Click OK.
image04
Before moving on, let's take a quick look around the WebMatrix user interface. In the lower-left part of the page you see that you can select one of four workspaces. When you open WebMatrix and select a site, you start off in the Site workspace, which lets you perform tasks like specifying site settings (for example, designating a default web page) and monitoring HTTP requests.
To create, delete, and update files such as web pages, select the Files workspace. The site's folder structure appears in the left pane, and when you select a file, you can edit it in the content pane on the right.
image05
To add a database to your site and then add tables and data to it, select the Databases workspace. You get a list of databases in the left pane, and the content pane changes depending on what you want to do with a selected database.
image06
Finally, to get information about how to help your site rank high in search engine results, select the Reports workspace. Once you've run some reports, you'll see them listed on the left, and when you select one, you'll see the reports contents on the right.
image07
You might have noticed that across the top of the page is a Quick Access Toolbar and a ribbon, like in Microsoft Office 2010. Some of the buttons on the ribbon's Home tab are different in each workspace, but the buttons in the Site group are always the same.
image08
You use My Sites to choose a site to work on, Publish to make the site publicly available, Run to test the site in a browser, andStart/Stop/Restart to work with the web server that you'll use in WebMatrix to test your website (IIS Express).  You'll learn more about IIS Express in a minute.

Adding an ASP.NET Web Page to Your Site

To get a feel for how to work in WebMatrix and what you can do with it, begin by creating a web page. Select the Files workspace and then clickNew. You get a list of templates to choose from for various file types.
image09
Select the CSHTML template and call the new page Default.cshtml. The extension .cshtml indicates that this is an ASP.NET Web page. It can contain HTML, JavaScript, and CSS, just like a normal HTML page, and you can make the page dynamic by adding special code that runs on the server.
Click OK.
The CSHTML template creates a new page with some basic HTML.
image10
As you can see, this is ordinary HTML markup.  Add some simple "Hello World" HTML to it.
image11
Now click the Default.cshtml file in the navigation pane and then click the Run button to see this page in the browser.
image12

Creating Dynamic Web Pages

You can use helpers in ASP.NET Web pages to create dynamic web pages with a minimum of code. A helper packages commonly used functionality in a way that's easy to write code for. (In other words, helpers package functionality that it would be a lot more trouble to implement if you had to code it all yourself.)  To use helpers, you have to install the Microsoft ASP.NET Helpers Library.
Click Run to run the Default.cshtml file again. In the address box of your browser, remove the Default.cshtml file name from the URL and replace it with _Admin. The resulting URL will look similar to the following (it's ok if your URL displays a port number other than 8080):
http://localhost:8080/_Admin
Press Enter to browse to a page that lets you administer your site. Because this is the first time you're logging into the _Admin page, it prompts you to create a password and guides you through some steps to ensure your site's security. After you do that, click Install packages from an online feed.
image12a
Next, click the Install button next to the ASP.NET Web Helpers Library 1.1 package.
image12b
On the next page, click Install to start the installation.
image12c
When the installation completes, the _Admin page displays the result.
image12d
Now that you have the helpers installed, we'll show you how simple it is to create dynamic (programmed) web pages. Go back to WebMatrix. In theFiles workspace, click New. Create a new CSHTML page named Twitter.cshtml and add some HTML and code to it:
image13
In this example, just a single line of code displays a box of dynamically scrolling tweets from a Twitter user. The Twitter user in this case is "Microsoft". Twitter.Profile is an example of how to use a helper. This is just one of many helpers that ASP.NET makes available. Other helpers do things like upload and crop images, play video clips, and display data from a database.
Select the Twitter.cshtml file in the navigation pane and then click Run, and there they are -- the tweets you asked for are in your browser. (The style of the box is fully customizable, of course; this is the default appearance.)
image14
That's all there is to it—you've created a page that displays a Twitter feed, using simple HTML and one ASP.NET helper.
For more information about using WebMatrix Helpers and programming with Razor Syntax, see the WebMatrix Book.

Testing Your Site

WebMatrix includes IIS Express, which works much like IIS, the commercial Web server from Microsoft. However, IIS Express is integrated with WebMatrix and runs on your local computer, which makes it easy to test your site without having to copy your files to a public server and test them there.
Sometimes you need to do more than just see how pages look in a browser in order to test a site. You might want to know what's going on behind the scenes when a request comes in to your site. For example, are there broken links in your pages? The Requests tool lets you know where there might be problems in your site, and it can take you directly to the file to make a fix.
Select the Site workspace and then click Requests in the ribbon to see the Requests tool, and then click Only Errors to see only the errors.
image15
The first two examples show that a 404.0 error code was issued because your site does not have a favorites icon. To see details about the error, you can click the line with the 404. WebMatrix then shows you details about the error, the name of the page that contains the broken link, and links to resources for more information.
image16
For more information about using WebMatrix to analyze requests to your website, see Analyze Requests to your Website.

Working with Data

Many websites need to keep information in a database. WebMatrix includes Microsoft SQL Server Compact 4.0, which you can use to create databases for your website without the need for full SQL Server. With SQL Server Compact, it's easy to publish your website, because everything is in files in your website folder. (If your website traffic grows and you need more database capabilities, WebMatrix also can automate the process of migrating your data to full SQL Server.)
Whether you use SQL Server Compact or full SQL Server, you can use WebMatrix to create a database, create tables and columns, and add and display data. To see how to work with a database, switch to the Databases workspace. Add a database by clicking New Database.
image17
Next, create a table and define some columns for it. In the navigation pane, click Tables, and then click New Table in the ribbon to create the table.  Click New Column to add columns in the table designer. Add the following columns:
image18
Click the Save icon in the Quick Access Toolbar and name the table Product.
image18-5
Next, select the new table in the navigation pane. In the ribbon, click Data to use the built-in table data editor to add some data:
image19
Ok, you've got some data … now how do you display it? Easily, using another ASP.NET helper, namely the WebGrid helper. In the Files workspace, create another CSHTML page named ListProducts.cshtml and add the following code:
@{
    var db=Database.Open("WebMatrixDemo");
    var grid=new WebGrid(db.Query("SELECT * FROM Product ORDER BY Name"));
}
<!DOCTYPE html>
<html>
    <head>
        <title>Products</title>
        <style type="text/css">
            table {border-collapse:  collapse;}
            td, th {border:  solid 1px; }
        </style>
    </head>
    <body>
        <h1>Products</h1>
        @grid.GetHtml()
    </body>
</html>
Select the ListProducts.cshtml file in the navigation pane and then click Run. The browser displays a simple table with sortable columns:
image20

Optimizing Your Site

WebMatrix has a built in search-engine optimization (SEO) tool that inspects your website and provides suggestions that can help increase the ranking for your web pages. The tool shows you the optimizations that you can make, and points you directly to the pages that you need to edit. To create a report, select the Reports workspace and click Create a report for the site in the content pane.  The report lists the errors that were found.
image21
This report says there's a problem with the one of the pages. Double-click the localhost URL to expand it and see what the problem is.
image22
For each error, WebMatrix explains what the problem is, makes recommendations for fixing it, and provides links to more information. At this point, you can click Edit this page, which will take you directly to the page in the editor where you can fix the problem, or you can click View More Details to get more information about the error. In this case, if you click Edit this page, WebMatrix will open the Default.cshtml file so that you can add the missing description.
For more information about using the Reports feature in WebMatrix, see Use WebMatrix to optimize your site for search engines.

Getting on the Web

When you're ready to show your application to the world, WebMatrix helps you by introducing you to web hosting partners so that you can find the one that meets your needs.  On the ribbon, click Publish, and then select Find Web Hosting to see hosting offers in your browser.
image23
To publish your site, WebMatrix has built-in support for FTP and Microsoft Web Deploy, which is a one-click publishing solution. Once you've established an account with a hosting provider, import or enter your account settings into the WebMatrix tool. Then all you have to do to publish your site directly from WebMatrix is click Publish. It's as easy as that!
image24
For more information about publishing with WebMatrix, see How to Publish a Web Application Using WebMatrix.

Learn More

There's a lot that we haven't covered here—we've barely scratched the surface. To learn more, including how you can use open source applications, monitor your site's performance, or what other helpers are available, visit http://www.asp.net. For more information about SQL Server Compact, seeSQL Server Compact.
To learn more about WebMatrix and the Microsoft Web Platform, see the following websites:
Alternatively, you may have noticed that there is an Online Help button you can click in the top right corner in WebMatrix. Once you go to this Learnpage, you'll find more resources about all aspects of WebMatrix, you'll be able to find help in forums, or file bugs and suggestions directly to the WebMatrix product team!