The Top Features in ASP.NET Web Pages 2
by Microsoft
This article provides an overview of the top new features in the ASP.NET Web Pages 2 RC, a lightweight web programming framework that is included with Microsoft WebMatrix 2 RC.
What’s included:
- Installing WebMatrix
- Changes for the RC release
- Changes for the Beta release
- Using the New and Updated Site Templates
- Validating User Input
- Enabling logins from Facebook and other sites using OAuth and OpenID
- Adding Maps using the Maps Helper
- Running Web Pages Applications Side by Side
- Rendering Pages for Mobile Devices
[!NOTE] This topic assumes that you are using WebMatrix to work with your ASP.NET Web Pages 2 code. However, as with Web Pages 1, you can also create Web Pages 2 websites using Visual Studio, which gives you enhanced IntelliSense capabilities and debugging. To work with Web Pages in Visual Studio, you must first install Visual Studio 2010 SP1, Visual Web Developer Express 2010 SP1, or Visual Studio 11 Beta. Then install the ASP.NET MVC 4 Beta, which includes templates and tools for creating ASP.NET MVC 4 and Web Pages 2 applications in Visual Studio.
Last update: 18 June 2012
To install Web Pages, you can use the Microsoft Web Platform Installer, which is a free application that makes it easy to install and configure web-related technologies. You will install the WebMatrix 2 Beta, which includes Web Pages 2 Beta.
Browse to the installation page for the latest version of the Web Platform Installer:
https://go.microsoft.com/fwlink/?LinkId=226883
[!NOTE] If you already have WebMatrix 1 installed, this installation updates it to WebMatrix 2 Beta. You can run websites that were created using version 1 or 2 on the same computer. For more information, see the section on Running Web Pages Applications Side by Side.
Choose Install Now.
If you use Internet Explorer, go to the next step. If you use a different browser like Mozilla Firefox or Google Chrome, you are prompted to save the Webmatrix.exe file to your computer. Save the file and then click it to launch the installer.Run the installer and choose the Install button. This installs WebMatrix and Web Pages.
New and Enhanced Features
Changes for the RC Version (June 2012)
The RC version release in June 2012 has a few changes from the Beta version refresh that was released in March 2012. These changes are:
- A
Validation.AddFormError
method was added to theValidation
helper. This is useful if you perform validation manually (for example, you validate a value that is passed in the query string) and you want to add an error message that can be displayed by theHtml.ValidationSummary
method. For more information, see the section Validating Data That Doesn’t Come Directly From Users in Validating User Input in ASP.NET Web Pages (Razor) Sites. - The functionality for bundling and minification has been removed from the core ASP.NET Web Pages 2 assemblies. As a consequence, the
Assets
helper listed later in this document is not available. Instead, you must install the ASP.NET Optimization NuGet package. For more information, see Bundling and Minifying Assets in an ASP.NET Web Pages (Razor) Site. - Additional assemblies to support ASP.NET Web Pages 2 have been added. The only noticeable effect of this change is that you might see more assemblies in a site’s bin folder after you create a site or deploy a site to a hosting provider.
### Changes for the Beta Version (February 2012)
The Beta version released in February 2012 has only a few changes from the Beta version that was released in December 2011. These changes are:
Razor now supports conditional attributes. In an HTML element, if you set an attribute to a value that resolves in server code to
false
ornull
, ASP.NET does not render the attribute at all. For example, imagine you have the following markup for a check box:[!code-htmlMain]
1: <input type="checkbox"
2: name="check1"
3: value="check1"
4: checked="@checked1" />
checked1
resolves tofalse
or tonull
, thechecked
attribute is not rendered. This is a breaking change.- The
Validation.GetHtml
method has been renamed toValidation.For
. This is a breaking change;Validation.GetHtml
will not work in the Beta release. You can now include the
~
operator in markup to reference the site root without using theHref
function. (That is, the Razor parser can now find and resolve the~
operator without requiring an explicit method call toHref
.) TheHref
method still works, so this is not a breaking change.For example, if you previously had markup like this:
<a href="@Href("~/Default.cshtml")">Home</a>
You can now use markup like this:
<a href="~/Default.cshtml">Home</a>
The
Scripts
helper for assets (resource) management has been replaced with theAssets
helper, which has slightly different methods, such as the following:- For
Scripts.Add
, useAssets.AddScript
- For
Scripts.GetScriptTags
, useAssets.GetScripts
This is a breaking change; the
Scripts
class is not available in the Beta release. The code examples in this document that use asset management have been updated with this change.- For
### Using the New and Updated Site Templates
The Starter Site template has been updated so that it runs on Web Pages 2 by default. It also includes the following new capabilities:
- Mobile-friendly page rendering. Through the use of CSS styles and the
@media
selector, the Starter Site provides improved rendering of pages on smaller screens, including mobile device screens. - Improved membership and authentication options. You can let users log into your site using their accounts from other social networking sites, such as Twitter, Facebook, and Windows Live. For more information, see the Enabling Logins from Facebook and Other Sites using OAuth and OpenID section.
- HTML5 elements.
The new Personal Site template lets you create a website that contains a personal blog, a photos page, and a Twitter page. You can customize a site based on the Personal Site template by doing the following:
- Change the look of the site by editing the layout file (_SiteLayout.cshtml) and the styles file (Site.css).
- Install NuGet packages that add functionality to your site. For information about how to install packages, including the ASP.NET Web Helpers Library, see the tutorial about installing helpers.
To access the Personal Site template, choose Templates on the WebMatrix Quick Start screen.
In the Templates dialog box, choose the Personal Site template.
The landing page of the Personal Site template lets you follow links to set up your blog, Twitter page, and photos page.
In Web Pages 1, to validate user input on submitted forms, you use the System.Web.WebPages.Html.ModelState
class. (This is illustrated in several of the code samples in the Web Pages 1 tutorial titled Working with Data.) You can still use this approach in Web Pages 2. However, Web Pages 2 also offers improved tools for validating user input:
- New validation classes, including
System.Web.WebPages.ValidationHelper
andSystem.Web.WebPages.Validator
, that let you do powerful validation tasks with a few lines of code. - Optionally, client-side validation, which provides immediate feedback to the user instead of requiring a round trip to the server to check for validation errors. (For security reasons, validation is performed on the server even if the checks have been performed in the client beforehand.)
To use the new validation features, do the following:
In the page’s code, register an element to be validated by using methods of the Validation
helper: Validation.RequireField
, Validation.RequireFields
(to register multiple elements to be required), or Validation.Add
. The Add
method lets you specify other types of validation checks, like data-type checking, comparing entries in different fields, string-length checks, and patterns (using regular expressions). Here are some examples:
[!code-htmlMain]
1: Validation.RequireField("text1");
2: Validation.RequireField("text1", "The text1 field is required");
3: Validation.RequireFields("text1", "text2", "text3");
4:
5: Validation.Add("text1", Validation.StringLength(5));
6: Validation.Add("textDate", Validation.DateTime("Enter a date"));
7: Validation.Add("textCount", Validation.Integer("Enter a number"));
8: Validation.Add("textCount",
9: Validation.Range(1, 10, "Enter a value between 1 and 10"));
To display a field-specific error, call Html.ValidationMessage
in the markup for each element being validated:
[!code-cshtmlMain]
1: <input type="text" name="course"
2: value="@Request["course"]" />
3: @Html.ValidationMessage("course")
To display a summary (<ul>
list) of all the errors in the page, Html.ValidationSummary
in the markup:
[!code-cshtmlMain]
1: @Html.ValidationSummary()
These steps are enough to implement server-side validation. If you want to add client-side validation, do the following in addition.
Add the following script file references inside the <head>
section of a web page. The first two script references point to remote files on a content delivery network (CDN) server. The third reference points to a local script file.
[!code-htmlMain]
1: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>
2: <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
3: <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The easiest way to get a local copy of the jquery.validate.unobtrusive.min.js library is to create a new Web Pages site based on one of the site templates (such as Starter Site). The site created by the template includes jquery.validate.unobtrusive.js file in its Scripts folder, from which you can copy it to your site.
If your website uses a_SiteLayout page to control the page layout, you can include these script references in that page so that validation is available to all content pages. If you want to perform validation only on particular pages, you can use the assets manager to register the scripts on only those pages. To do this, call Assets.AddScript(path)
in the page that you want to validate and reference each of the script files. Then add a call to Assets.GetScripts
in the _SiteLayout page in order to render the registered <script>
tags. For more information, see the section Registering Scripts with the Assets Manager.
In the markup for an individual element, call the Validation.For
method. This method emits attributes that jQuery can hook in order to provide client-side validation. For example:
[!code-cshtmlMain]
1: <input type="text" name="course"
2: value="@Request["course"]"
3: @Validation.For("course")
4: />
5: @Html.ValidationMessage("course")
The following example shows a page that validates user input on a form. To run and test this validation code, do this:
- Create a new web site using one of the WebMatrix 2 site templates that includes a Scripts folder, such as the Starter Site template.
- In the new site, create a new .cshtml page, and replace the contents of the page with the following code.
- Run the page in a browser. Enter valid and invalid values to see the effects on validation. For example, leave a required field blank or enter a letter in the Credits field.
[!code-cshtmlMain]
1: @{
2: // Specify what fields users must fill in.
3: Validation.RequireFields("course", "professorname", "credits");
4: // Add validation criteria. Here, require that input to Credits is an integer.
5: Validation.Add("credits", Validator.Integer());
6:
7: if (IsPost) {
8: // Wrap the postback code with a validation check.
9: if (Validation.IsValid()) {
10: var course = Request["course"];
11: var professorName = Request["professorname"];
12: var credits = Request["credits"];
13: // Display valid input values.
14: <text>
15: You entered: <br />
16: Class: @course <br />
17: Professor: @professorName <br />
18: Credits: @credits <br />
19: </text>
20: }
21: }
22: }
23: <!DOCTYPE html>
24: <html lang="en">
25: <head>
26: <meta charset="utf-8" />
27: <title>Testing Validation in ASP.NET Web Pages version 2</title>
28: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>
29: <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js"></script>
30: <script src="@Href("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
31: </head>
32: <body>
33: <form method="post" action="">
34: <!-- Display a summary message about any validation issues. -->
35: @Html.ValidationSummary()
36: <fieldset>
37: <legend>Add Class</legend>
38: <div>
39: <label for="Course">Class:</label>
40: <!-- Validation.For("course") adds validation attributes to the input element. -->
41: <input type="text" name="Course" value="@Request["course"]" @Validation.For("course") />
42:
43: <!-- Display a field-specific message about validation issues. -->
44: @Html.ValidationMessage("course")
45: </div>
46:
47: <div>
48: <label for="ProfessorName">Professor:</label>
49: <input type="text" name="ProfessorName" value="@Request["professorname"]"
50: @Validation.For("professorname") />
51: @Html.ValidationMessage("professorname")
52: </div>
53:
54: <div>
55: <label for="Credits">Credits:</label>
56: <input type="text" name="Credits" value="@Request["credits"]" @Validation.For("credits") />
57: @Html.ValidationMessage("credits")
58: </div>
59:
60: <div>
61: <label> </label>
62: <input type="submit" value="Submit" class="submit" />
63: </div>
64: </fieldset>
65: </form>
66: </body>
67: </html>
Here is the page when a user submits valid input:
Here is the page when a user submits it with a required field left empty:
Here is the page when a user submits it with something other than an integer in the Credits field:
For more information, see the following blog posts:
- Updated validation in Web Pages v2 Basics of adding validation using the
Validation
helper (server-side only) - Updated validation in Web Pages v2, Part 2 Adding client-side validation.
- Updated validation in Web Pages v2, Part 3 Formatting validation errors.
### Registering Scripts Using the Assets Manager
The assets manager is a new feature that you can use in server code to register and render client scripts. This feature is helpful when you are working with code from multiple files (such as layout pages, content pages, helpers, etc.) that are combined into a single page at run time. The assets manager coordinates the source files to make sure that script files are referenced correctly and efficiently on the rendered page, regardless of which code files they are called from or how many times they are called. The assets manager also renders <script>
tags in the right place so that the page can load quickly (without downloading scripts while rendering) and to avoid errors that can occur if scripts are called before rendering is complete.
For example, suppose that you create a custom helper that calls a JavaScript file, and you call this helper at three different places in your content page code. If you don’t use the assets manager to register the script calls in the helper, three different <script>
tags that all point to the same script file will appear in your rendered page. Plus, depending on where the <script>
tags are inserted in the rendered page, errors may occur if the script tries to access certain page elements before the page fully loads. If you use the assets manager to register the script, you avoid these problems.
You can register a script with the assets manager by doing this:
- In the code that needs to reference the script, call the
Assets.AddScript
method. In a _SiteLayout page, call the
Assets.GetScripts
method to render the<script>
tags.[!NOTE] Put calls to
Assets.GetScripts
as the very last item in the<body>
element of the _SiteLayout page. This helps the page load faster and can help avoid script errors.
The following example shows how the assets manager works. The code contains the following items:
- A custom helper named
MakeNote
. This helper renders a string inside a box by wrapping adiv
element around it that’s styled with a border and by adding “Note:” to it. The helper also calls a JavaScript file that adds run-time behavior to the note. Rather than reference the script with a<script>
tag, the helper registers the script by callingAssets.AddScript
. - A JavaScript file. This is the file that’s called by the helper, and it temporarily increases the font size of note items during a
mouseover
event. - A content page, which references the_SiteLayout page, renders some content in the body, and then calls the
MakeNote
helper. - A _SiteLayout page. This page provides a common header and a page layout structure. It also includes a call to
Assets.GetScripts
, which is how the assets manager renders script calls in a page.
To run the sample:
- Create an empty Web Pages 2 website. You can use the WebMatrix Empty Site template for this.
- Create a folder named Scripts in the site.
- In the Scripts folder, create a file named Test.js, copy the Test.js content into it from the example, and save the file..
- Create a folder named App_Code in the site.
- In the App_Code folder, create a file named Helpers.cshtml, copy the example code into it, and save it in a folder named App_Code in the root folder.
- In the site’s root folder, create a file named _SiteLayout.cshtml, copy the example into it, and save the file.
- In the site root, create a file named ContentPage.cshtml, add the example code, and save it.
- Run ContentPage in a browser. The string you passed to the
MakeNote
helper is rendered as a boxed note. - Pass the mouse pointer over the note. The script temporarily increases the font size of the note.
- View the source of the rendered page. Because of where you placed the call to
Assets.GetScripts
, the rendered<script>
tag that calls Test.js is the very last item in the body of the page.
Test.js
[!code-javascriptMain]
1: function UpdateNoteStyle(id) {
2: var theNote = document.getElementById(id);
3: theNote.style.fontSize = "150%";
4: }
5: function ReturnNoteStyle(id) {
6: var theNote = document.getElementById(id);
7: theNote.style.fontSize = "inherit";
8: }
Helpers.cshtml
[!code-cshtmlMain]
1: @helper MakeNote(string content, string noteid) {
2: Assets.AddScript("~/Scripts/Test.js");
3:
4: <div id="@noteid" style="border: 1px solid black; width: 90%; padding: 5px; margin-left: 15px;"
5: onmouseover="UpdateNoteStyle('@noteid')" onmouseout="ReturnNoteStyle('@noteid')">
6: <p>
7: <strong>Note</strong> @content
8: </p>
9: </div>
10: }
_SiteLayout.cshtml
[!code-htmlMain]
1: <!DOCTYPE html>
2:
3: <html lang="en">
4: <head>
5: <meta charset="utf-8" />
6: <title></title>
7: </head>
8: <body>
9: <header>
10: <div class="content-wrapper">
11: <h1>Contoso Ltd.</h1>
12: </div>
13: </header>
14: <div id="body">
15: <section class="content-wrapper main-content clear-fix">
16: @RenderBody()
17: </section>
18: </div>
19: @Assets.GetScripts()
20: </body>
21: </html>
ContentPage.cshtml
[!code-cshtmlMain]
1: @{
2: Layout = "~/_SiteLayout.cshtml";
3: }
4: <p>
5: Nullam scelerisque facilisis placerat. Fusce a augue
6: erat, malesuada euismod dui.
7: </p>
8: @Helpers.MakeNote("Latin is fun to translate.", "note1")
The following screenshot shows ContentPage.cshtml in a browser when you hold the mouse pointer over the note:
### Enabling Logins from Facebook and Other Sites Using OAuth and OpenID
Web Pages 2 provides enhanced options for membership and authentication. The main enhancement is that there are new OAuth and OpenID providers. Using these providers, you can let users log into your site using their existing credentials from Facebook, Twitter, Windows Live, Google, and Yahoo. For example, to log in using a Facebook account, users can just choose a Facebook icon, which redirects them to the Facebook login page where they enter their user information. They can then associate the Facebook login with their account on your site. A related enhancement to the Web Pages membership features is that users can associate multiple logins (including logins from social networking sites) with a single account on your website.
This image shows the Login page from the Starter Site template, where a user can choose a Facebook, Twitter, or Windows Live icon to enable logging in with an external account:
You can enable OAuth and OpenID membership using just a few lines of code. The methods and properties you use to work with the OAuth and OpenID providers are in the WebMatrix.Security.OAuthWebSecurity
class.
However, instead of using code to enable logins from other sites, a recommended way to get started with the new providers is to use the new Starter Site template that is included with WebMatrix 2 Beta. The Starter Site template includes a full membership infrastructure, complete with a login page, a membership database, and all the code you need to let users log into your site using either local credentials or those from another site.
How to Enable Logins using the OAuth and OpenID Providers
This section provides an example of how to let users log in from external sites (Facebook, Twitter, Windows Live, Google, or Yahoo) to a site that’s based on the Starter Site template. After creating a starter site, you do this (details follow):
For the sites that use an OAuth provider (Facebook, Twitter, and Windows Live), create an application on the external site. This gives you application keys that you’ll need in order to invoke the login feature for those sites. For sites that use an OpenID provider (Google, Yahoo), you do not have to create an application. For all of these sites, you must have an account in order to log in and to create developer applications.
[!NOTE] Windows Live applications only accept a live URL for a working website, so you cannot use a local website URL for testing logins.
Edit a few files in your website in order to specify the appropriate authentication provider and to submit a login to the site you want to use.
To enable Google and Yahoo logins:
In your website, edit the _AppStart.cshtml page and add the following two lines of code in the Razor code block after the call to the
[!code-cssMain]WebSecurity.InitializeDatabaseConnection
method. This code enables both the Google and Yahoo OpenID providers.1: OAuthWebSecurity.RegisterOpenIDClient(BuiltInOpenIDClient.Google);
2: OAuthWebSecurity.RegisterOpenIDClient(BuiltInOpenIDClient.Yahoo);
In the ~/Account/Login.cshtml page, remove the comments from the following
[!code-htmlMain]<fieldset>
block of markup near the end of the page. To uncomment the code, remove the@*
characters that precede and follow the<fieldset>
block. The resulting code block looks like this:1: <fieldset>
2: <legend>Log in using another service</legend>
3: <input type="submit" name="provider" id="facebook" value="Facebook" title="Log in using your Facebook account." />
4: <input type="submit" name="provider" id="twitter" value="Twitter" title="Log in using your Twitter account." />
5: <input type="submit" name="provider" id="windowsLive" value="WindowsLive" title="Log in using your Windows Live account." />
6: </fieldset>
Add an
[!code-htmlMain]<input>
element for the Google or Yahoo provider to the<fieldset>
group in the ~/Account/Login.cshtml page. The updated<fieldset>
group with<input>
elements for both Google and Yahoo looks like the following example:1: <fieldset>
2: <legend>Log in using another service</legend>
3: <input type="submit" name="provider" id="facebook" value="Facebook" title="Log in using your Facebook account." />
4: <input type="submit" name="provider" id="twitter" value="Twitter" title="Log in using your Twitter account." />
5: <input type="submit" name="provider" id="windowsLive" value="WindowsLive" title="Log in using your Windows Live account." />
6: <input type="submit" name="provider" id="yahoo" value="Yahoo" title="Log in using your Yahoo account." />
7: <input type="submit" name="provider" id="google" value="Google" title="Log in using your Google account." />
8: </fieldset>
In the ~/Account/AssociateServiceAccount.cshtml page, add
<input>
elements for Google or Yahoo to the<fieldset>
group near the end of the file. You can copy the same<input>
elements that you just added to the<fieldset>
section in the ~/Account/Login.cshtml page.The ~/Account/AssociateServiceAccount.cshtml page in the Starter Site template can be used if you want to create a page on which users can associate multiple logins from other sites with a single account on your website.
Now you can test Google and Yahoo logins.
- Run the default.cshtml page of your site and choose the Log in button.
On the Login page, in the Use another service to log in section, choose either the Google or Yahoo submit button. This example uses the Google login.
The web page redirects the request to the Google login page.
- Enter credentials for an existing Google account.
If Google asks you whether you want to allow Localhost to use information from the account, click Allow.
The code uses the Google token to authenticate the user, and then returns to this page on your website. This page lets users associate their Google login with an existing account on your website, or they can register a new account on your site to associate the external login with.
Choose the Associate button. The browser returns to your application’s home page.
To enable Facebook logins:
- Go to the Facebook developers site (log in if you’re not already logged in).
- Choose the Create New App button, and then follow the prompts to name and create the new application.
- In the section Select how your app will integrate with Facebook, choose the Website section.
Fill in the Site URL field with the URL of your site (for example,
http://www.example.com
). The Domain field is optional; you can use this to provide authentication for an entire domain (such as example.com).[!NOTE] If you are running a site on your local computer with a URL like
http://localhost:12345
(where the number is a local port number), you can add this value to the Site URL field for testing your site. However, any time the port number of your local site changes, you will need to update the Site URL field of your application.- Choose the Save Changes button.
- Choose the Apps tab again, and then view the start page for your application.
- Copy the App ID and App Secret values for your application and paste them into a temporary text file. You will pass these values to the Facebook provider in your website code.
Exit the Facebook developer site.
Now you make changes to two pages in your website so that users will able to log into the site using their Facebook accounts.
In your website, edit the _AppStart.cshtml page and uncomment the code for the Facebook OAuth provider. The uncommented code block looks like the following:
[!code-xmlMain]1: OAuthWebSecurity.RegisterOAuthClient(
2: BuiltInOAuthClient.Facebook,
3: consumerKey: "", // for Facebook, consumerKey is called AppID in the SDK
4: consumerSecret: "");
- Copy the App ID value from the Facebook application as the value of the
consumerKey
parameter (inside the quotation marks). - Copy App Secret value from the Facebook application as the
consumerSecret
parameter value. - Save and close the file.
Edit the ~/Account/Login.cshtml page and remove the comments from the
[!code-htmlMain]<fieldset>
block near the end of the page. To uncomment the code, remove the@*
characters that precede and follow the<fieldset>
block. The code block with comments removed looks like the following:1: <fieldset>
2: <legend>Log in using another service</legend>
3: <input type="submit" name="provider" id="facebook" value="Facebook" title="Log in using your Facebook account." />
4: <input type="submit" name="provider" id="twitter" value="Twitter" title="Log in using your Twitter account." />
5: <input type="submit" name="provider" id="windowsLive" value="WindowsLive" title="Log in using your Windows Live account." />
6: </fieldset>
Save and close the file.
Now you can test the Facebook login.
- Run the site’s default.cshtml page and choose the Login button.
On the Login page, in the Use another service to log in section, choose the Facebook icon.
The web page redirects the request to the Facebook login page.
Log into a Facebook account.
The code uses the Facebook token to authenticate you and then returns to a page where you can associate your Facebook login with your site’s login. Your user name or email address is filled into the Email field on the form.
Choose the Associate button.
The browser returns to the home page and you are logged in.
To enable Twitter logins:
- Browse to the Twitter developers site.
- Choose the Create an App link and then log into the site.
- On the Create an Application form, fill in the Name and Description fields.
In the WebSite field, enter the URL of your site (for example,
http://www.example.com
).[!NOTE] If you’re testing your site locally (using a URL like
http://localhost:12345
), Twitter might not accept the URL. However, you might be able to use the local loopback IP address (for examplehttp://127.0.0.1:12345
). This simplifies the process of testing your application locally. However, every time the port number of your local site changes, you’ll need to update the WebSite field of your application.- In the Callback URL field, enter a URL for the page in your website that you want users to return to after logging into Twitter. For example, to send users to the home page of the Starter Site (which will recognize their logged-in status), enter the same URL that you entered in the WebSite field.
- Accept the terms and choose the Create your Twitter application button.
- On the My Applications landing page, choose the application you created.
- On the Details tab, scroll to the bottom and choose the Create My Access Token button.
- On the Details tab, copy the Consumer Key and Consumer Secret values for your application and paste them into a temporary text file. You’ll pass these values to the Twitter provider in your website code.
Exit the Twitter site.
Now you make changes to two pages in your website so that users will be able to log into the site using their Twitter accounts.
In your website, edit the _AppStart.cshtml page and uncomment the code for the Twitter OAuth provider. The uncommented code block looks like this:
[!code-csharpMain]1: OAuthWebSecurity.RegisterOAuthClient(
2: BuiltInOAuthClient.Twitter,
3: consumerKey: "",
4: consumerSecret: "");
- Copy the Consumer Key value from the Twitter application as the value of the
consumerKey
parameter (inside the quotation marks). - Copy the Consumer Secret value from the Twitter application as the value of the
consumerSecret
parameter. - Save and close the file.
Edit the ~/Account/Login.cshtml page and remove the comments from the
[!code-htmlMain]<fieldset>
block near the end of the page. To uncomment the code, remove the@*
characters that precede and follow the<fieldset>
block. The code block with comments removed looks like the following:1: <fieldset>
2: <legend>Log in using another service</legend>
3: <input type="submit" name="provider" id="facebook" value="Facebook" title="Log in using your Facebook account." />
4: <input type="submit" name="provider" id="twitter" value="Twitter" title="Log in using your Twitter account." />
5: <input type="submit" name="provider" id="windowsLive" value="WindowsLive" title="Log in using your Windows Live account." />
6: </fieldset>
Save and close the file.
Now you can test the Twitter login.
- Run the default.cshtml page of your site and choose the Login button.
On the Login page, in the Use another service to log in section, choose the Twitter icon.
The web page redirects the request to a Twitter login page for the application you created.
- Log into a Twitter account.
The code uses the Twitter token to authenticate the user and then returns you to a page where you can associate your login with your website account. Your name or email address is filled into the Email field on the form.
Choose the Associate button.
The browser returns to the home page and you are logged in.
### Adding Maps Using the Maps Helper
Web Pages 2 includes additions to the ASP.NET Web Helpers Library, which is a package of add-ins for a Web Pages site. One of these is a mapping component provided by the Microsoft.Web.Helpers.Maps
class. You can use the Maps
class to generate maps based either on an address or on a set of longitude and latitude coordinates. The Maps
class lets you call directly into popular map engines including Bing, Google, MapQuest, and Yahoo.
To use the new Maps
class in your website, you must first install the version 2 of the Web Helpers Library. To do this, go to the instructions for installing the currently released version of the ASP.NET Web Helpers Library and install version 2.
The steps for adding mapping to a page are the same regardless of which of the map engines you call. You just add a JavaScript file reference to your mapping page and then add a call that renders the <script>
tags on your page. Then on your mapping page, call the map engine you want to use.
The following example shows how to create a page that renders a map based on an address, and another page that renders a map based on longitude and latitude coordinates. The address mapping example uses Google Maps, and the coordinate mapping example uses Bing Maps. Note the following elements in the code:
- The call to
Assets.AddScript
at the top of the two mapping pages. This method adds a reference to the jquery-1.6.2.min.js file that is included with the Starter Site template and that’s required by theMaps
class. - The call to the
Assets.GetScripts
method in the layout file. This method renders the<script>
tag on the two mapping pages. - The call to the
@Maps.GetGoogleHtml
and the@Maps.GetBingHtml
methods in the mapping pages. To map an address, you must pass an address string. To map coordinates, you must pass longitude and latitude coordinates. For the Bing Maps engine, you must also pass a key (which you get for free by signing up at the Bing Maps Developers site). The methods for the other map engines work in a similar way (@Maps.GetYahooHtml
,@Maps.GetMapQuestHtml
).
To create mapping pages:
- Create a website based on the Starter Site template.
- Create a file named MapAddress.cshtml in the root of the site. This page will generate a map based on an address that you pass to it.
Copy the following code into the file, overwriting the existing content.
[!code-cshtmlMain]1: @{
2: Layout = "~/_MapLayout.cshtml";
3: Assets.AddScript("~/Scripts/jquery-1.6.2.min.js");
4: }
5:
6: <div id="navigation">
7: <h3>Map an Address:</h3>
8: <form method="post" action="" id="coordinates" style="width: 320px">
9: <fieldset>
10: <div>
11: <label for="address">Address:</label>
12: <input style="width: 300px" type="text" name="address" value="@Request["address"]"/>
13: <input type="submit" value="Map It!" />
14: </div>
15: </fieldset>
16: </form>
17: </div>
18: <div id="content">
19: @if(IsPost) {
20: var theAddress = Request["address"];
21: @Maps.GetGoogleHtml(theAddress,
22: width: "800",
23: height: "800")
24: }
25: </div>
- Create a file named _MapLayout.cshtml in the root of the site. This page will be the layout page for the two mapping pages.
Copy the following code into the file, overwriting the existing content.
[!code-htmlMain]1: <!DOCTYPE html>
2:
3: <html lang="en">
4: <head>
5: <meta charset="utf-8" />
6:
7: <title></title>
8: <style type="text/css">
9: #navigation {
10: position: absolute;
11: top: 1em;
12: left: 3em;
13: width: 18em;
14: }
15: #content {
16: margin-top: 10em;
17: margin-left: 3em;
18: }
19: </style>
20: </head>
21: <body>
22: @RenderBody()
23:
24: @*
25: Call the Assets helper to render tags for the Maps helper. For
26: releases after Web Pages 2 Beta, call Assets.GetScripts().
27: *@
28: @Assets.GetScripts()
29: </body>
30: </html>
- Create a file named MapCoordinates.cshtml in the root of the site. This page will generate a map based on a set of coordinates that you pass to it.
Copy the following code into the file, overwriting the existing content.
[!code-cshtmlMain]
1: @{
2: Layout = "~/_MapLayout.cshtml";
3: Assets.AddScript("~/Scripts/jquery-1.6.2.min.js");
4: }
5:
6: <div id="navigation">
7: <h3>Map a set of coordinates:</h3>
8: <form method="post" action="" id="coordinates">
9: <fieldset>
10: <div>
11: <label for="latitude">Latitude: </label>
12: <input type="text" name="latitude" value="@Request["latitude"]"/>
13: </div>
14: <div>
15: <label for="longitude">Longitude:</label>
16: <input type="text" name="longitude" value="@Request["longitude"]"/>
17: </div>
18: <div>
19: <input type="submit" value="Map It!" />
20: </div>
21: </fieldset>
22: </form>
23: </div>
24: <div id="content">
25: @if(IsPost) {
26: var theLatitude = Request["latitude"];
27: var theLongitude = Request["longitude"];
28: @Maps.GetBingHtml("Ag6C5Ci9VUGz9AIhQyJ7YNwGraanqwy5-V3LK1qGDpdEVPV-MUPBryG18ELoC6g6",
29: "",
30: theLatitude,
31: theLongitude,
32: width: "800",
33: height: "800")
34: }
35: </div>
To test your mapping pages:
- Run the page MapAddress.cshtml file.
Enter a full address string including a street address, state or province, and postal code, and then choose the Map It button. The page renders a map from Google Maps:
- Find a set of latitude and longitude coordinates for a specific location.
Run the page MapCoordinates.cshtml. Enter the coordinates and then choose the Map It button. The page renders a map from Bing Maps:
### Running Web Pages Applications Side by Side
Web Pages 2 adds the ability to run applications side by side. This lets you continue to run your Web Pages 1 applications, build new Web Pages 2 applications, and run all of them on the same computer.
Here are some things to remember when you install the Web Pages 2 Beta with WebMatrix:
- By default, existing Web Pages applications will run as version 2 applications on your computer. (The assemblies for version 2 are installed in the GAC and will be used automatically.)
If you want to run a site using Web Pages version 1 (instead of the default, as in the previous point), you can configure the site to do that. If your site doesn’t already have a web.config file in the root of the site, create a new one and copy the following XML into it, overwriting the existing content. If the site already contains a web.config file, add an
[!code-xmlMain]<appSettings>
element like the following one to the<configuration>
section.1: <?xml version="1.0"?>
2: <configuration>
3: <appSettings>
4: <add key="webPages:Version" value="1.0"/>
5: </appSettings>
6: </configuration>
New applications that you create using the site templates in Web Matrix version 2 Beta include the Web Pages version 2 assemblies in the site’s bin folder.
In general, you can always control which version of Web Pages to use with your site by using NuGet to install the appropriate assemblies into the site’s bin folder. To find packages, visit NuGet.org.
### Rendering Pages for Mobile Devices
Web Pages 2 lets you create custom displays for rendering content on mobile or other devices.
The System.Web.WebPages
namespace contains the following classes that let you work with display modes: DefaultDisplayMode
, DisplayInfo
, and DisplayModes
. You can use these classes directly and write code that renders the right output for specific devices.
Alternatively, you can create device-specific pages by using a file-naming pattern like this: FileName.Mobile.cshtml. For example, you can create two versions of a page, one named MyFile.cshtml and one named MyFile.Mobile.cshtml. At run time, when a mobile device requests MyFile.cshtml, Web Pages renders the content from MyFile.Mobile.cshtml. Otherwise, MyFile.cshtml is rendered.
The following example shows how to enable mobile rendering by adding a content page for mobile devices. Page1.cshtml contains content plus a navigation sidebar. Page1.Mobile.cshtml contains the same content, but omits the sidebar.
To build and run the code sample:
- In a Web Pages site, create a file named Page1.cshtml and copy the Page1.cshtml content into it from the example.
- Create a file named Page1.Mobile.cshtml and copy the Page1.Mobile.cshtml content into it from the example. Notice that the mobile version of the page omits the navigation section for better rendering on a smaller screen.
- Run a desktop browser and browse to Page1.cshtml.
Run a mobile browser (or a mobile device emulator) and browse to Page1.cshtml. Notice that this time Web Pages renders the mobile version of the page.
[!NOTE] To test mobile pages, you can use a mobile device simulator that runs on a desktop computer. This tool lets you test web pages as they would look on mobile devices (that is, typically with a much smaller display area). One example of a simulator is the User Agent Switcher add-on for Mozilla Firefox, which lets you emulate various mobile browsers from a desktop version of Firefox.
Page1.cshtml
[!code-htmlMain]
1: <!DOCTYPE html>
2:
3: <html lang="en">
4: <head>
5: <meta charset="utf-8" />
6: <title></title>
7: <style type="text/css">
8: #navigation {
9: position: absolute;
10: top: 0;
11: left: 0;
12: width: 10em;
13: }
14: #content {
15: margin-left: 13em;
16: margin-right: 10em;
17: }
18: </style>
19: </head>
20: <body>
21: <div id="navigation">
22: <h3>Related Sites</h3>
23: <ul>
24: <li><a href="http://www.adventure-works.com/">Adventure Works</a></li>
25: <li><a href="http://www.contoso.com/">Contoso, Ltd</a></li>
26: <li><a href="http://www.treyresearch.net/">Trey Research</a></li>
27: </ul>
28: </div>
29: <div id="content">
30: <h1>Lorem ipsum dolor</h1>
31: <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
32: eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
33: At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
34: no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit
35: amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
36: labore et dolore magna aliquyam erat, sed diam voluptua. </p>
37: <p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
38: gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum
39: dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
40: ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam
41: et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
42: sanctus est Lorem ipsum dolor sit amet.</p>
43: </div>
44: </body>
45: </html>
Page1.Mobile.cshtml
[!code-htmlMain]
1: <!DOCTYPE html>
2:
3: <html lang="en">
4: <head>
5: <meta charset="utf-8" />
6: <title></title>
7: <style type="text/css">
8: #content {
9: margin-left: 2em;
10: margin-right: 5em;
11: }
12: </style>
13: </head>
14: <body>
15: <div id="content">
16: <h1>Lorem ipsum dolor</h1>
17: <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
18: eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
19: At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
20: no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit
21: amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
22: labore et dolore magna aliquyam erat, sed diam voluptua. </p>
23: <p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
24: gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum
25: dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
26: ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam
27: et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
28: sanctus est Lorem ipsum dolor sit amet.</p>
29: </div>
30: </body>
31: </html>
Page1.cshtml rendered in a desktop browser:
Page1.Mobile.cshtml displayed in an Apple iPhone simulator view in the Firefox browser. Even though the request is to Page1.cshtml, the application renders Page1.Mobile.cshtml.
ASP.NET Web Pages 1 Resources
[!NOTE] Most Web Pages 1 programming and API resources still apply to Web Pages 2.
WebMatrix Resources
- WebMatrix 2 What’s New
- Microsoft WebMatrix Site
- Starting Web Development with Microsoft WebMatrix(includes a full-length sample Web Pages application)
|