diff --git "a/ASP.NET/Introducing%20ASP.NET%20Web%20Pages%202.pdf.txt" "b/ASP.NET/Introducing%20ASP.NET%20Web%20Pages%202.pdf.txt" new file mode 100644--- /dev/null +++ "b/ASP.NET/Introducing%20ASP.NET%20Web%20Pages%202.pdf.txt" @@ -0,0 +1,6877 @@ +Introducing ASP.NET Web Pages 2 + +Mike Pope + +Summary: 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. The + +tutorials take you from novice programmer through seeing your site live on the + +Internet. Topics include how to install Microsoft WebMatrix (a set of tools for + +creating sites); how to work with forms; how to display, add, update, and delete + +data; how to create a consistent site layout; and how to publish to the Web. + +Category: Step-by-Step + +Applies to: ASP.NET Web Pages 2 RC, Visual Studio 2012 RC + +Source: ASP.NET site (link to source content) + +E-book publication date: June 2012 + + + + + + + + + + + + + + + + + +Copyright © 2012 by Microsoft Corporation + +All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any +means without the written permission of the publisher. + +Microsoft and the trademarks listed at +http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the +Microsoft group of companies. All other marks are property of their respective owners. + +The example companies, organizations, products, domain names, email addresses, logos, people, places, and +events depicted herein are fictitious. No association with any real company, organization, product, domain name, +email address, logo, person, place, or event is intended or should be inferred. + +This book expresses the author’s views and opinions. The information contained in this book is provided without +any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or +distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this +book. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +2 + + + + + + + + +Contents + +Tutorial 1: Getting Started ............................................................................................................. 4 +Tutorial 2: Programming Basics ................................................................................................... 19 +Tutorial 3: Displaying Data ........................................................................................................... 39 +Tutorial 4: HTML Form Basics ...................................................................................................... 56 +Tutorial 5: Entering Database Data by Using Forms ...................................................................... 70 +Tutorial 6: Updating Database Data ............................................................................................. 82 +Tutorial 7: Deleting Database Data .............................................................................................. 97 +Tutorial 8: Creating a Consistent Layout .................................................................................... 104 +Tutorial 9: Publishing a Site by Using WebMatrix ....................................................................... 118 +Appendix: Code Listings ............................................................................................................. 127 + +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.) +Downloads: Completed website for the ASP.NET Web Pages introductory tutorial + +Note This tutorial is based on the ASP.NET Web Pages version 2 RC and Microsoft +WebMatrix 2 RC. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +3 + + + +Tutorial 1: Getting Started + +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 + +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +4 + + + +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +5 + +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: + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +6 + + +And here's the page that lets you add new movie information to your site: + +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +7 + + +This button takes you to the Web Platform Installer page on the Microsoft.com site. + +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +8 + + + + +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 the Start menu, launch Microsoft WebMatrix. + +In Windows, start Microsoft WebMatrix. + +To begin, you'll create a blank website and add a page. In the next tutorial set, you'll use one of +the built-in website templates. + +In the start window, click Templates. Templates are prebuilt files and pages for different types of +websites. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +9 + + + +In the Quick Start window, select Empty Site and name the new site "WebPagesMovies". + +Click Next. + +WebMatrix creates and opens the site: + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +10 + + + +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 (Site, Files, +Databases, Reports). 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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +11 + + +In the ribbon, click the arrow under New and then click 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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +12 + + + + + +Click OK. + +WebMatrix creates the page and opens it in the 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
and 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.) + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +13 + + + + + + + + + +@{ + +} + + + + + + +Hello World!
+ + + +In the Quick Access Toolbar or in the File menu, click Save. + +Testing the Page + +In the Files workspace, right-click the HelloWorld.cshtml page and then click Launch in browser. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +14 + + + + + +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +15 + + + + + + + +localhost and port numbers + +Notice that when you test a page in WebMatrix, the URL in the browser is something like +http://localhost:33651/HelloWorld.cshtml. The name localhost refers to a local server, meaning +that the page is served by a web server that's on your own computer. As noted, WebMatrix +includes a web server program named IIS Express that runs when you launch a page. + +The number after localhost (for example, localhost:33651) refers to a port number on your +computer. This is the number of the "channel" that IIS Express uses for this particular website. +The port number is selected at random from the range 1024 through 65536 when you create your +site, and it's different for every site that you create. (When you test your own site, the port +number will almost certainly be a different number than 33561.) By using a different port for each +website, IIS Express can keep straight which of your sites it's talking to. + +Later when you publish your site to a public web server, you no longer see localhost in the URL. At +that point, you'll see a more typical URL like http://myhostingsite/mywebsite/HelloWorld.cshtml +or whatever the page is. You'll learn more about publishing a site later in this tutorial series. + +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 a variable named currentDateTime. You'll read more about Razor syntax in the next +tutorial. + +In the body of the page, after theHello World!
element, add the following: + +Right now it's @currentDateTime
+ +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. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +16 + +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: + + + + + + +Hello World!
+Right now it's 1/18/2012 2:49:50 PM
+ + + +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: + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +17 + + + +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. + +Additional Resources + +• HTML Tutorial on the W3Schools site. + +Introducing ASP.NET Web Pages 2 + +Tutorial 1: Getting Started + +18 + + +Tutorial 2: Programming Basics + +This tutorial gives you an overview of how to program in ASP.NET Web Pages with Razor syntax. + +What you'll learn: + +Some basic C#, which is the programming language you'll use. +Some fundamental programming concepts for Web Pages. + +• The basic "Razor" syntax that you use for programming in ASP.NET Web Pages. +• +• +• How to install packages (components that contain prebuilt code) to use with your site. +• How to use helpers to perform common programming tasks. + +Features/technologies discussed: + +• NuGet and the package manager. +• The Twitter helper. + +This tutorial is primarily an exercise in introducing you to the programming syntax that you'll use +for ASP.NET Web Pages. You'll learn about Razor syntax and code that's written in the C# +programming language. You got a glimpse of this syntax in the previous tutorial; in this tutorial +we'll explain the syntax more. + +We promise that this tutorial involves the most programming that you'll see in a single tutorial, +and that it's the only tutorial that is only about programming. In the remaining tutorials in this set, +you'll actually create pages that do interesting things. + +You'll also learn about helpers. A helper is a component — a packaged-up piece of code — that +you can add to a page. The helper performs work for you that otherwise might be tedious or +complex to do by hand. + +Creating a Page to Play with Razor + +In this section you'll play a bit with Razor so you can get a sense of the basic syntax. + +Start WebMatrix if it's not already running. You'll use the website you created in the previous +tutorial (Getting Started). To reopen it, click Open Site and choose My Sites: + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +19 + +Choose the WebPagesMovies site, and then click OK. + +Select the Files workspace. + +In the ribbon, click New to create a page. Select CSHTML and name the new page +TestRazor.cshtml. + +Click OK. + +Copy the following into the file, completely replacing what's there already. + +Note When you copy code or markup from the examples into a page, the indentation and +alignment might not be the same as in the tutorial. Indentation and alignment don't affect +how the code runs, though. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +20 + + + + + + +@{ + // Working with numbers + var a = 4; + var b = 5; + var theSum = a + b; + + // Working with characters (strings) + var technology = "ASP.NET"; + var product ="Web Pages"; + + // Working with objects + var rightNow = DateTime.Now; +} + + + + +The value of a is @a. The value of b is @b. +
The sum of a and b is @theSum.
+The product of a and b is @(a*b).
+The technology is @technology, and the product is @product.
+Together they are @(technology + " " + +product)
+The current date and time is: @rightNow
+The URL of the current page is@Request.Url
element. The markup also +contains an element to create a Submit button. + +Run the page to see how it works now. For now, it's basically a static page, even if you click the +Submit button. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +26 + +Go back to WebMatrix. Inside the code block, add the following code after the line that initializes +message: + +if(IsPost){ + message = "Now you've submitted the page."; +} + +The if{ } block + +What you just added was an if condition. In code, the if condition has a structure like this: + +if(some condition){ +One or more statements here that run if the condition is true; +} + +The condition to test is in parentheses. It has to be a value or an expression that returns true or +false. If the condition is true, ASP.NET runs the statement or statements that are inside the +braces. (Those are the then part of the if-then logic.) If the condition is false, the block of code is +skipped. + +Here are a few examples of conditions you can test in an if statement: + +if( currentValue > 12 ){ ... } + +if( dueDate <= DateTime.Today ) { ... } + +if( IsDone == true ) { ... } + +if( IsPost ) { ... } + +if( !IsPost ) { ... } + +if(a != 0) { ... } + +if( fileProcessingIsDone != true && displayMessage == false ) { ... } + +You can test variables against values or against expressions by using a logical operator or +comparison operator: equal to (==), greater than (>), less than (<), greater than or equal to (>=), +and less than or equal to (<=). The != operator means not equal to — for example, if(a != 0) +means if a is not equal to 0. + +Note Make sure you notice that the comparison operator for equals to (==) is not the +same as =. The = operator is used only to assign values (var a=2). If you mix these +operators up, you'll either get an error or you'll get some strange results. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +27 + + + + + + + +To test whether something is true, the complete syntax is if(IsDone == true). But you can also +use the shortcut if(IsDone). If there's no comparison operator, ASP.NET assumes that you're +testing for true. + +The ! operator by itself means a logical NOT. For example, the condition if(!IsPost) means if +IsPost is not true. + +You can combine conditions by using a logical AND (&& operator) or logical OR (|| operator). For +example, the last of the if conditions in the preceding examples means if FileProcessingIsDone is +set to true AND displayMessage is set to false. + +The else block + +One final thing about if blocks: an if block can be followed by an else block. An else block is +useful is you have to execute different code when the condition is false. Here's a simple example: + +var message = ""; +if(errorOccurred == true) +{ + message = "Sorry, an error occurred."; +} +else +{ + message = "The process finished without errors!"; +} + +You'll see some examples in later tutorials in this series where using an else block is useful. + +Testing whether the request is a submit (post) + +There's more, but let's get back to the example, which has the condition if(IsPost){ ... }. +IsPost is actually a property of the current page. The first time the page is requested, IsPost +returns false. However, if you click a button or otherwise submit the page — that is, you post it — +IsPost returns true. So IsPost lets you determine whether you're dealing with a form submission. +(In terms of HTTP verbs, if the request is a GET operation, IsPost returns false. If the request is a +POST operation, IsPost returns true.) In a later tutorial you'll work with input forms, where this +test becomes particularly useful. + +Run the page. Because this is the first time you're requested the page, you see "This is the first +time you've requested the page". That string is the value that you initialized the message variable +to. There's an if(IsPost) test, but that returns false at the moment, so the code inside the if +block doesn't run. + +Click the Submit button. The page is requested again. As before, the message variable is set to +"This is the first time ...".But this time, the test if(IsPost) returns true, so the code inside the + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +28 + +ifblock runs. The code changes the value of the message variable to a different value, which is +what's rendered in the markup. + +Now add an if condition in the markup. Below the
element that contains the Submit button, +add the following markup: + +@if(IsPost){ +
You submitted the page at @DateTime.Now
+} + +You're adding code inside the markup, so you have to start with @. Then there's an if test similar +to the one you added earlier up in the code block. Inside the braces, though, you're adding +ordinary HTML — at least, it's ordinary until it gets to @DateTime.Now. This is another little bit of +Razor code, so again you have to add @ in front of it. + +The point here is that you can add if conditions in both the code block at the top and in the +markup. If you use an if condition in the body of the page, the lines inside the block can be +markup or code. In that case, and as is true anytime you mix markup and code, you have to use @ +to make it clear to ASP.NET where the code is. + +Run the page and click Submit.This time you not only see a different message when you submit +("Now you've submitted ..."), but you see a new message that lists the date and time. + +Testing the value of a query string + +One more test. This time, you'll add an if block that tests a value named show that might be +passed in the query string.(Like this: http://localhost:43097/TestRazorPart2.cshtml?show=true) +You'll change the page so that the message you've been displaying ("This is the first time ...", etc.) +is only displayed if the value of show is true. + +At the bottom (but inside) the code block at the top of the page, add the following: + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +29 + + + +var showMessage = false; +if(Request.QueryString["show"].AsBool() == true){ + showMessage = true; +} + +The complete code block now looks like the following example. (Remember that when you copy +the code into your page, the indentation might look different. But that doesn't affect how the +code runs.) + +@{ + var message = "This is the first time you've requested the page."; + + if(IsPost){ + message = "Now you've submitted the page."; + } + + var showMessage = false; + if(Request.QueryString["show"].AsBool() == true){ + showMessage = true; + } +} + +The new code in the block initializes a variable named showMessage to false. It then does an if test +to look for a value in the query string. When you first request the page, it has a URL like this one: + +http://localhost:43097/TestRazorPart2.cshtml + +The code determines whether the URL contains a variable named show in the query string, like this +version of the URL: + +http://localhost:43097/TestRazorPart2.cshtml?show=true + +The test itself looks at the QueryString property of the Request object. If the query string contains +an item named show, and if that item is set to true, the if block runs and sets the showMessage +variable to true. + +There's a trick here, as you can see. Like the name says, the query string is a string. However, you +can only test for true and false if the value you're testing is a Boolean (true/false) value. Before +you can test the value of the show variable in the query string, you have to convert it to a Boolean +value. That's what the AsBool method does — it takes a string as input and converts it to a +Boolean value. Clearly, if the string is "true", the AsBool method converts that value to true.If the +value of the string is anything else, AsBool returns false. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +30 + + + + +Data Types and As( ) Methods + +We've only said so far that when you create a variable, you use the keyword var. That's not the +entire story, though. In order to manipulate values — to add numbers, or concatenate strings, or +compare dates, or test for true/false — C# has to work with an appropriate internal +representation of the value. C# can usually figure out what that representation should be (that is, +what type the data is) based on what you're doing with the values. Now and then, though, it can't +do that. If not, you have to help out by explicitly indicating how C# should represent the data. The +AsBool method does that — it tells C# that a string value of "true" or "false" should be treated as +a Boolean value. Similar methods exist to represent strings as other types as well, like AsInt (treat +as an integer), AsDateTime (treat as a date/time), AsFloat (treat as a floating-point number), and +so on. When you use these As( ) methods, if C# can't represent the string value as requested, +you'll see an error. + +In the markup of the page, remove or comment out this element (here it's shown commented +out): + + + +Right where you removed or commented out that text, add the following: + +@if(showMessage){ +@message
+} + +The if test says that if the showMessage variable is true, render aelement with the value of the +message variable. + +Summary of your conditional logic + +In case you're not entirely sure of what you've just done, here's a summary. + +• The message variable is initialized to a default string ("This is the first time ..."). +• + +If the page request is the result of a submit (post), the value of message is changed to +"Now you've submitted ..." + +• The showMessage variable is initialized to false. +• +• + +If the query string contains ?show=true , the showMessage variable is set to true. +In the markup, if showMessage is true, a
element is rendered that shows the value of +message. (If showMessage is false, nothing is rendered at that point in the markup.) +In the markup, if the request is a post, a
element is rendered that displays the date +and time. + +• + +Run the page. There's no message, because showMessage is false, so in the markup the +if(showMessage) test returns false. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +31 + +Click Submit. You see the date and time, but still no message. + +In your browser, go to the URL box and add the following to the end of the URL: ?show=true and +then press Enter. + +The page is displayed again. (Because you changed the URL, this is a new request, not a submit.) +Click Submit again. The message is displayed again, as is the date and time. + +In the URL, change ?show=true to ?show=false and press Enter. Submit the page again. The page is +back to how you started — no message. + +As noted earlier, the logic of this example is a little contrived. However, if is going to come up in +many of your pages, and it will take one or more of the forms you've seen here. + +Installing a Helper (Displaying a Twitter Feed) + +Some tasks that people often want to do on web pages require a lot of code or require extra +knowledge. Examples: displaying a chart for data; putting a Facebook "Like" button on a page; +sending email from your website; cropping or resizing images; using PayPal for your site. To make +it easy to do these kinds of things, ASP.NET Web Pages lets you use helpers. Helpers are +components that you install for a site and that let you perform typical tasks by using just a few +lines of Razor code. + +ASP.NET Web Pages has a few helpers built in. However, many helpers are available in packages +(add-ins) that are provided using the NuGet package manager. NuGet lets you select a package to +install and then it takes care of all the details of the installation. + +In this part of the tutorial, you'll install a helper that lets you manage a Twitter feed. You'll learn +two things. One is how to find and install a helper. You'll also learn how a helper makes it easy to +do something you'd otherwise need to do by using a lot of code you'd have to write yourself. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +32 + + + +In WebMatrix, click the Gallery button. + +This launches the NuGet package manager and displays available packages. (Not all of the +packages are helpers; some add functionality to WebMatrix itself, some are additional templates, +and so on.) + +In the search box, enter "Twitter". NuGet shows the packages that have Twitter functionality. +(The link underneath the package icon links to details about that package.) + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +33 + + + + +Select the Twitter.Helper package and then click Install to launch the installer. When it's +done,you see a message in the notification area at the bottom of the screen. + +That's it. NuGet downloads and installs everything, including any additional components that +might be required (dependencies). Since this is the first time you've installed a helper, NuGet also +creates folders in your website for the code that makes up the helper. + +If for some reason you have to uninstall a helper, the process is very similar. Click the Gallery +button, click the Installed tab, and pick the package you want to uninstall. + +Using a Helper in a Page + +Now you'll use the Twitter helper that you just installed. The process for adding a helper to a page +is similar for most helpers. + +In WebMatrix, create a page and name it TwitterTest.cshml. (You're creating a special page to test +the helper, but you can use helpers in any page in your site.) + +Inside the
element, add a