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 Page + + +

Hello World Page

+

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 the

Hello 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 Page + + +

Hello World Page

+

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; +} + + + + +Testing Razor Syntax + + + + +

Testing Razor Syntax

+
+ +
+

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

+
+ +
+ + + +Examining the Example Page + +Most of what you see is ordinary HTML. However, at the top there's this code block: + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +21 + + + + + + + + + + @{ + // 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; +} + +Notice the following things about this code block: + +• The @ character tells ASP.NET that what follows is Razor code, not HTML. ASP.NET will + +treat everything after the @ character as code until it runs into some HTML again. (In this +case, that's the element. + +• The braces ( { and } ) enclose a block of Razor code if the code has more than one line. + +The braces tell ASP.NET where the code for that block starts and ends. + +• The // characters mark a comment — that is, a part of the code that won't execute. + +• Each statement has to end with a semicolon (;). (Not comments, though.) + +• You can store values in variables, which you create (declare) with the keyword var.When + +you create a variable, you give it a name, which can include letters, numbers, and +underscore (_). Variable names can't start with a number and can't use the name of a +programming keyword (like var). + +• You enclose character strings (like "ASP.NET" and "Web Pages") in quotation marks. (They + +must be double quotation marks.) Numbers are not in quotation marks. + +• Whitespace outside of quotation marks doesn't matter. Line breaks mostly don't matter; +the exception is that you can't split a string in quotation marks across lines. Indentation +and alignment don't matter. + +Something that's not obvious from this example is that all code is case sensitive. This means that +the variable TheSum is a different variable than variables that might be named theSum or thesum. +Similarly, var is a keyword, but Var is not. + +Objects and properties and methods + +Then there's the expression DateTime.Now. In simple terms, DateTime is an object. An object is a +thing that you can program with—a page, a text box, a file, an image, a web request, an email +message, a customer record, etc. Objects have one or more properties that describe their +characteristics. A text box object has a Text property (among others), a request object has a + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +22 + + + + Urlproperty (and others), an email message has a From property and a To property, and so on. +Objects also have methods that are the "verbs" they can perform. You'll be working with objects a +lot. + +As you can see from the example, DateTime is an object that lets you program dates and times. It +has a property named Now that returns the current date and time. + +Using code to render markup in the page + +In the body of the page, notice the following: + +
+

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

+
+ +Again, the @ character tells ASP.NET that what follows is code, not HTML. In the markup you can +add @ followed by a code expression, and ASP.NET will render the value of that expression right at +that point. In the example, @a will render whatever the value is of the variable named a, @product +renders whatever is in the variable named product, and so on. + +You're not limited to variables, though. In a few instances here, the @ character precedes an +expression: + +• + +• + +• + +@(a*b) renders the product of whatever is in the variables a and b. (The * operator means +multiplication.) +@(technology + " " + product) renders the values in the variables technology and +product after concatenating them and adding a space in between. The operator (+) for +concatenating strings is the same as the operator for adding numbers. ASP.NET can +usually tell whether you're working with numbers or with strings and does the right thing +with the + operator. +@Request.Url renders the Url property of the Request object. The Request object contains +information about the current request from the browser, and of course the Url property +contains the URL of that current request. + +The example is also designed to show you that you can do work in different ways. You can do +calculations in the code block at the top, put the results into a variable, and then render the + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +23 + + + + variable in markup. Or you can do calculations in an expression right in the markup. The approach +you use depends on what you're doing and, to some extent, on your own preference. + +Seeing the code in action + +Right-click the name of the file and then choose Launch in browser. You see the page in the +browser with all the values and expressions resolved in the page. + +(Remember that the URL that you see in the browser might use a different port number than +what you see in these screenshots. Instead of locahost:56011, you'll see localhost followed by a +different number.) + +Look at the source in the browser. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +24 + + + As you expect from your experience in the previous tutorial, none of the Razor code is in the page. +All you see are the actual display values. When you run a page, you're actually making a request +to the web server that's built into WebMatrix. When the request is received, ASP.NET resolves all +the values and expressions and renders their values into the page. It then sends the page to the +browser. + +Razor and C# + +Up to now we've said that you're working with Razor syntax. That's true, but it's not the complete +story. The actual programming language you're using is called C#. C# was created by Microsoft +over a decade ago and has become one of the primary programming languages for creating +Windows apps. All the rules you've seen about how to name a variable and how to create +statements and so on are actually all rules of the C# language. + +Razor refers more specifically to the small set of conventions for how you embed this code into a +page. For example, the convention of using @ to mark code in the page and using @{ } to embed a +code block is the Razor aspect of a page. Helpers are also considered to be part of Razor. Razor +syntax is used in more places than just in ASP.NET Web Pages. (For example, it's used in ASP.NET +MVC views as well.) + +We mention this because if you look for information about programming ASP.NET Web Pages, +you'll find lots of references to Razor. However, a lot of those references don't apply to what +you're doing and might therefore be confusing. And in fact, many of your programming questions +are really going to be about either working with C# or working with ASP.NET. So if you look +specifically for information about Razor, you might not find the answers you need. + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +25 + + + Adding Some Conditional Logic + +One of the great features about using code in a page is that you can change what happens based +on various conditions. In this part of the tutorial, you'll play around with some ways to change +what's displayed in the page. + +The example will be simple and somewhat contrived so that we can concentrate on the +conditional logic. The page you'll create will do this: + +• + +Show different text on the page depending on whether it's the first time the page is +displayed or whether you've clicked a button to submit the page. That will be the first +conditional test. + +• Display the message only if a certain value is passed in the query string of the URL + +(http://...?show=true). That will be the second conditional test. + +In WebMatrix, create a page and name it TestRazorPart2.cshtml. (In the ribbon, click New, choose +CSHTML, name the file, and then click OK.) + +Replace the contents of that page with the following: + +@{ + var message = "This is the first time you've requested the page."; +} + + + +Testing Razor Syntax - Part 2 + + + + +

Testing Razor Syntax - Part 2

+
+
+

@message

+

+
+
+ + + +The code block at the top initializes a variable named message with some text. In the body of the +page, the contents of the message variable are displayed inside a

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 a

element 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

element. Inside the
element, type this: + +@TwitterGoodies. + +The @ character is the same character you've been using to mark Razor code. TwitterGoodies is +the helper object that you're working with. + +As soon as you type the period (.), WebMatrix displays a list of methods (functions) that the +TwitterGoodies helper makes available: + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +34 + + + + This feature is known as IntelliSense. It helps you code by providing context-appropriate choices. +IntelliSense works with HTML, CSS, ASP.NET code, JavaScript, and other languages that are +supported in WebMatrix. It's another feature that makes it easier to develop web pages in +WebMatrix. + +Press S on the keyboard, and you see that IntelliSense finds the Search method: + +Press Tab. IntelliSense inserts the selected method (Search) for you. Type an open parenthesis ( ( +), then the string "webmatrix" in quotation marks, then a closing parenthesis ( ) ). When you're +done, the line looks like this: + +@TwitterGoodies.Search("webmatrix") + +The Search method finds tweets that contain the string that you specify — in this case, it will look +for tweets that mention "webmatrix". (Either in text or in hashtags.) + +Run the page. You see a Twitter feed. (It might take a few moments for the feed to start +populating.) + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +35 + + + To get an idea of what the helper is doing for you, view the source of the page in the +browser.Along with the HTML that you had in your page, you see a block of JavaScript code that +looks roughly like the following block. (It might be all on one line or otherwise compressed.) + + + +This is code that the helper rendered into the page at the place where you had +@TwitterGoodies.Search. (There's also some markup that's not shown here.) The helper took the +information you provided and generated the code that talks directly to Twitter in order to get +back the Twitter feed that you see. If you know the Twitter programming interface (API), you can +create this code yourself. But because the helper can do it for you, you don't have to know the +details of how to communicate with Twitter. And even if you are familiar with the Twitter API, it's +a lot easier to include the TwitterGoodies helper on the page and let it do the work. + +Return to the page. At the bottom, inside the element, add the following code. Substitute +your own Twitter account name if you have one. + +
+ @TwitterGoodies.FollowButton("microsoft") +
+ +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +36 + + + This code calls the FollowButton method of the TwitterGoodies helper. As you can guess, the +method adds a Follow Me on Twitter button. You pass a Twitter name to this method to indicate +who to follow. + +Run the page and you see the Follow Me button: + +Click it, and you go to the Twitter page for the user you specified. + +As before, you can look at the source of the page in the browser to see what the Twitter helper +generated for you. This time the code looks something like the following example: + +Follow microsoft on Twitter + +Again, you could have written this code yourself, but the helper makes it much easier. + +Server-Side (Razor) and Client-Side (JavaScript) Programming + +How does Razor code in an ASP.NET Web Pages relate to JavaScript code that runs in the +browser? If you've got experience with JavaScript, you might realize as you work with these +tutorials that many of the tasks could also be done in JavaScript. That's true, especially with the +simple examples you've seen so far. + +A .cshtml page can contain both Razor code and JavaScript code. The traditional division of labor +has been that server code handled tasks that it made sense to run on the server. This included +accessing resources like a shared database and performing various types of business logic. In +contrast, client code has typically been used to create a rich user experience. Pop-up calendars, +sliders, animations, and many other UI effects are created by client code, and can all be done +easily using JavaScript libraries (especially jQuery). + +These days the distinction has blurred a little because client code libraries now let you +communicate with the server in ways that formerly could only be done in server code. In general, +though, it's still useful to think of server code (Razor and C#) as being for back-end work and client +code (JavaScript) as useful for UI. In subsequent tutorial sets you'll learn how to integrate +JavaScript into a .cshtml page for just this purpose, namely to create a lively user experience. + +Coming Up Next + +To keep this tutorial short, we had to focus on only a few basics. Naturally, there's a lot more to +Razor and C#. You'll learn more as you go through these tutorials. If you're interested in learning + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +37 + + + more about the programming aspects of Razor and C# right now, you can read a more thorough +introduction here:Introduction to ASP.NET Web Programming Using the Razor Syntax. + +The next tutorial introduces you to working with a database. In that tutorial, you'll begin creating +the sample application that lets you list your favorite movies. + +Additional Resources + +• Complete Listing for Test Razor Page +• Complete Listing for TestRazorPart2 Page +• Complete Listing for TwitterTest Page +• + +Introduction to ASP.NET Web Programming Using the Razor Syntax + +Introducing ASP.NET Web Pages 2 + +Tutorial 2: Programming Basics + +38 + + Tutorial 3: Displaying Data + +This tutorial shows you how to create a database in WebMatrix and how to display database data +in a page when you use ASP.NET Web Pages (Razor). + +What you'll learn: + +• How to use WebMatrix tools to create a database and database tables. +• How to use WebMatrix tools to add data to a database. +• How to display data from the database on a page. +• How to run SQL commands in ASP.NET Web Pages. +• How to customize the WebGrid helper to change the data display and to add paging and + +sorting. + +Features/technologies discussed: + +• WebMatrix database tools. +• + +WebGrid helper. + +What You'll Build + +In the previous tutorial, you were introduced to ASP.NET Web Pages (.cshtml files), to the basics +of Razor syntax, and to helpers. In this tutorial, you'll begin creating the actual web application +that you'll use for the rest of the series. The app is a simple movie application that lets you view, +add, change, and delete information about movies. + +When you're done with this tutorial, you'll be able to view a movie listing that looks like this page: + +But to begin, you have to create a database. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +39 + + + A Very Brief Introduction to Databases + +This tutorial will provide only the briefest introduction to databases. If you have database +experience, you can skip this short section. + +A database contains one or more tables that contain information — for example, tables for +customers, orders, and vendors,or for students, teachers, classes, and grades. Structurally, a +database table is like a spreadsheet. Imagine a typical address book. For each entry in the address +book (that is, for each person) you have several pieces of information such as first name, last +name, address, email address, and phone number. + +(Rows are sometimes referred to as records, and columns are sometimes referred to as fields.) + +For most database tables, the table has to have a column that contains a unique value, like a +customer number, account number, and so on. This value is known as the table's primary key, and +you use it to identify each row in the table. In the example, the ID column is the primary key for +the address book shown in the previous example. + +Much of the work you do in web applications consists of reading information out of the database +and displaying it on a page. You'll also often gather information from users and add it to a +database, or you'll modify records that are already in the database. (We'll cover all of these +operations in the course of this tutorial set.) + +Database work can be enormously complex and can require specialized knowledge. For this +tutorial set, though, you have to understand only basic concepts, which will all be explained as +you go. + +Creating a Database + +WebMatrix includes tools that make it easy to create (or define) a database and to create tables in +the database. For this tutorial set, you'll create a database that has only one table in it — Movies. + +Open WebMatrix if you haven't already done so, and open the WebPagesMovies site that you +created in the previous tutorial. + +In the left pane, click the Database workspace. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +40 + + + The ribbon changes to show database-related tasks. In the ribbon, click New Database. + +WebMatrix creates a database (an .sdf file) that has the same name as your site — +WebPagesMovies.sdf. (You won't do this here, but you can rename the file to anything you like, as +long as it has an .sdf extension.) + +Creating a Table + +In the ribbon, click New Table. WebMatrix opens the table designer in a new tab. (If the New +Table option isn't available, make sure that the new database is selected in the tree view on the +left.) + +In the text box at the top (where the watermark says "Enter table name"), enter "Movies". + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +41 + + + + + The pane underneath the table name is where you define individual columns. For the Movies +table in this tutorial, you'll create only a few columns: ID, Title, Genre, and Year. + +In the Name box, enter "ID". Entering a value here activates all the controls for the new column. + +Tab to the Data Type list and choose int. This value specifies that the ID column will contain +integer (number) data. + +Note We won't call it out any more here (much), but you can use standard Windows +keyboard gestures to navigate in this grid. For example, you can tab between fields, you +can just start typing in order to select an item in a list, and so on. + +Tab past the Default Value box (that is, leave it blank). Tab to the Is Primary Key check box and +select it. This option tells the database that the ID column will contain the data that identifies +individual rows. (That is, each row will have a unique value in the ID column that you can use to +find that row.) + +Choose the Is Identity option. This option tells the database that it should automatically generate +the next sequential number for each new row. (The Is Identity option works only if you've also +selected the Is Primary Key option.) + +Click in the next grid row, or press Tab twice to finish the current row. Either gesture saves the +current row and starts the next one. Notice that the Default Value column now says Null. (Null is +the default value for the default value, so to speak.) + +When you've finished defining the new ID column, the designer will look like this illustration: + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +42 + + + To create the next column, click in the box in the Name column. Enter "Title" for the column and +then select nvarchar for the Data Type value. The "var" part of nvarchar tells the database that +the data for this column will be a string whose size might vary from record to record. (The "n" +prefix represents "national," which indicates that the field can hold character data for any +alphabet or writing system — that is, the field holds Unicode data.) + +When you choose nvarchar, another box appears where you can enter the maximum length for +the field. Enter 50, on the assumption that no movie title that you'll work with in this tutorial will +be longer than 50 characters. + +Skip Default Value and clear the Allow Nulls option. You don't want the database to allow any +movies to be entered into the database that don't have a title. + +When you're done and move to the next row, the designer looks like this illustration: + +Repeat these steps to create a column named "Genre", except for the length, set it to just 30. + +Create another column named "Year." For the data type, choose nchar (not nvarchar) and set the +length to 4. For the year, you're going to use a 4-digit number like "1995" or "2010", so you don't +require a variable-sized column. + +Here's what the finished design looks like: + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +43 + + + + + Press Ctrl+S or click the Save button in the Quick Access toolbar. Close the database designer by +closing the tab. + +Adding Some Example Data + +Later in this tutorial series you'll create a page where you can enter new movies in a form. For +now, however, you can add some example data that you can then display on a page. + +In the Database workspace in WebMatrix, notice that there's a tree that shows you the .sdf file +you created earlier. Open the node for your new .sdf file, and then open the Tables node. + +Right-click the Movies node and then choose Data. WebMatrix opens a grid where you can enter +data for the Movies table: + +Click the Title column and enter "When Harry Met Sally". Move to the Genre column (you can use +the Tab key) and enter "Romantic Comedy". Move to the Year column and enter "1989": + +Press Enter, and WebMatrix saves the new movie. Notice that the ID column has been filled in. + +Enter another movie (for example, "Gone with the Wind", "Drama", "1939"). The ID column is +filled in again: + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +44 + + + + + + Enter a third movie (for example, "Ghostbusters", "Comedy"). As an experiment, leave the Year +column blank and then press Enter. Because you unselected the Allow Nulls option, the database +shows an error: + +Click OK to go back and fix the entry (the year for "Ghostbusters" is 1984), and then press Enter. + +Fill in several movies until you have 8 or so. (Entering 8 makes it easier to work with paging later. +But if that's too many, enter just a few for now.) The actual data doesn't matter. + +If you entered all the movies without any errors, the ID values are sequential. If you tried to save +an incomplete movie record, the ID numbers might not be sequential. If so, that's okay. The +numbers don't have any inherent meaning, and the only thing that's important is that they're +unique in the Movies table. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +45 + + + + + Close the tab that contains the database designer. + +Now you can turn to displaying this data on a web page. + +Adding the Web Data Package + +You access data in ASP.NET Web Pages sites using helpers that are available in the WebData +package. Because you used the Empty Site template in WebMatrix to create your Movies site, the +WebData package isn't automatically included. Therefore, you have to add the package to your +site. + +In the left pane, click the Files workspace. + +In the ribbon, click the Gallery button. + +The NuGet Gallery is displayed. + +In the search box, enter "Microsoft.AspNet.WebPages.WebData" to narrow down the list of +packages that are displayed. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +46 + + + + Select the Microsoft ASP.NET Web Pages 2 Web Data package and then click Install. + +The Gallery page displays details about the package. + +Click Install. After you accept the license, WebMatrix installs the Web Data package. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +47 + + + + Now you're ready to display data on a page. + +Displaying Data in a Page by Using the WebGrid Helper + +To display data in a page, you're going to use the WebGrid helper. This helper produces a display in +a grid or table (rows and columns). As you'll see, you'll be able refine the grid with formatting and +other features. + +To run the grid, you'll have to write a few lines of code. These few lines will serve as a kind of +pattern for almost all of the data access that you do in this tutorial. + +Note You actually have many options for displaying data on a page; the WebGrid helper is +just one. We chose it for this tutorial because it's the easiest way to display data and +because it's reasonably flexible. In the next tutorial set, you'll see how to use a more +"manual" way to work with data in the page, which gives you more direct control over how +to display the data. + +In the left pane in WebMatrix, click the Files workspace. In the tree view, select the root of the +website. + +The new database you created is in the App_Data folder. If the folder didn't already exist, +WebMatrix created it for your new database. (The folder might have existed if you'd previously +installed helpers.) + +In the ribbon, click New. In the Choose a File Type box, choose CSHTML. + +In the Name box, name the new page "Movies.cshtml": + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +48 + + Click the OK button. WebMatrix opens a new file with some skeleton elements in it. First you'll +write some code to go get the data from the database. Then you'll add markup to the page to +actually display the data. + +Writing the Data Query Code + +At the top of the page, between the @{ and } characters, enter the following code. (Make sure +that you enter this code between the opening and closing braces.) + +var db = Database.Open("WebPagesMovies"); +var selectedData = db.Query("SELECT * FROM Movies"); +var grid = new WebGrid(source: selectedData); + +The first line opens the database that you created earlier, which is always the first step before +doing something with the database. You tell the Database.Open method name of the database to +open. Notice that you don't include .sdf in the name. The Open method assumes that it's looking +for an .sdf file (that is, WebPagesMovies.sdf) and that the .sdf file is in the App_Data folder. +(Earlier we noted that the App_Data folder is reserved; this scenario is one of the places where +ASP.NET makes assumptions about that name.) + +When the database is opened, a reference to it is put into the variable named db. (Which could be +named anything.) The db variable is how you'll end up interacting with the database. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +49 + + + The second line actually fetches the database data by using the Query method. Notice how this +code works: the db variable has a reference to the opened database, and you invoke the Query +method by using the db variable (db.Query). + +Thequery itself is a SQL Select statement. (For a little background about SQL, see the explanation +later.) In the statement, Movies identifies the table to query. The * character specifies that the +query should return all the columns from the table. (You could also list columns individually, +separated by commas.) + +The results of the query, if any, are returned and made available in the selectedData variable. +Again, the variable could be named anything. + +Finally, the third line tells ASP.NET that you want to use an instance of the WebGrid helper. You +create (instantiate) the helper object by using the new keyword and pass it the query results via +the selectedData variable. The new WebGrid object, along with the results of the database query, +are made available in the grid variable. You'll need that result in a moment to actually display the +data in the page. + +At this stage, the database has been opened, you've gotten the data you want, and you've +prepared the WebGrid helper with that data. Next is to create the markup in the page. + +Structured Query Language (SQL) + +SQL is a language that's used in most relational databases for managing data in a database. It +includes commands that let you retrieve data and update it, and that let you create, modify, and +manage data in database tables. SQL is different than a programming language (like C#). With +SQL, you tell the database what you want, and it's the database's job to figure out how to get the +data or perform the task. Here are examples of some SQL commands and what they do: + +Select * From Movies + +SELECT ID, Name, Price FROM Product WHERE Price > 10.00 ORDER BY Name + +The first Select statement gets all the columns (specified by *) from the Movies table. + +The second Select statement fetches the ID, Name, and Price columns from records in the +Product table whose Price column value is more than 10. The command returns the results in +alphabetical order based on the values of the Name column. If no records match the price criteria, +the command returns an empty set. + +INSERT INTO Product (Name, Description, Price) VALUES ('Croissant', 'A flaky delight', +1.99) + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +50 + + This command inserts a new record into the Product table, setting the Name column to +"Croissant", the Description column to "A flaky delight", and the price to 1.99. + +Notice that when you're specifying a non-numeric value, the value is enclosed in single quotation +marks (not double quotation marks, as in C#). You use these quotation marks around text or date +values, but not around numbers. + +DELETE FROM Product WHERE ExpirationDate < '01/01/2008' + +This command deletes records in the Product table whose expiration date column is earlier than +January 1, 2008. (The command assumes that the Product table has such a column, of course.) +The date is entered here in MM/DD/YYYY format, but it should be entered in the format that's +used for your locale. + +The Insert and Delete commands don’t return result sets. Instead, they return a number that +tells you how many records were affected by the command. + +For some of these operations (like inserting and deleting records), the process that's requesting +the operation has to have appropriate permissions in the database. That's why for production +databases you often have to supply a user name and password when you connect to the +database. + +There are dozens of SQL commands, but they all follow a pattern like the commands you see +here. You can use SQL commands to create database tables, count the number of records in a +table, calculate prices, and perform many more operations. + +Adding Markup to Display the Data + +Inside the element, set contents of the element to "Movies": + +<head> +<meta charset="utf-8" /> +<title>Movies + + +Inside the element of the page, add the following: + +

Movies

+
+ @grid.GetHtml() +
+ +That's it. The grid variable is the value you created when you created the WebGrid object in code +earlier. + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +51 + + In the WebMatrix tree view, right-click the page and select Launch in browser.You'll see +something like this page: + +(Remember that the URL that you see in the browser might use a different port number than +what you see in these screenshots — instead of locahost:56011, you'll see localhost followed by a +different number.) + +Click a column heading link to sort by that column. Being able to sort by clicking a heading is a +feature that's built into the WebGrid helper. + +The GetHtml method, as its name suggests, generates markup that displays the data. By default, +the GetHtml method generates an HTML element. (If you want, you can verify the +rendering by looking at the source of the page in the browser.) + +Modifying the Look of the Grid + +Using the WebGrid helper like you just did is easy, but the resulting display is plain. The WebGrid +helper has all sorts of options that let you control how the data is displayed. There are far too +many to explore in this tutorial, but this section will give you an idea of some of those options. A +few additional options will be covered in later tutorials in this series. + +Specifying Individual Columns to Display + +To start, you can specify that you want to display only certain columns. By default, as you've seen, +the grid shows all four of the columns from the Movies table. + +In the Movies.cshtml file, replace the @grid.GetHtml() markup that you just added with the +following: + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +52 + + + + + @grid.GetHtml( + columns: grid.Columns( + grid.Column("Title"), + grid.Column("Genre"), + grid.Column("Year") + ) +) + +To tell the helper which columns to display, you include a columns parameter for the GetHtml +method and pass in a collection of columns. In the collection, you specify each column to include. +You specify an individual column to display by including a grid.Column object, and pass in the +name of the data column you want. (These columns must be included in the SQL query results — +the WebGrid helper cannot display columns that were not returned by the query.) + +Launch the Movies.cshtml page in the browser again, and this time you get a display like the +following one (notice that no ID column is displayed): + +Changing the Look of the Grid + +There are quite a few more options for displaying columns, some of which will be explored in later +tutorials in this set. For now, this section will introduce you to ways in which you can style the grid +as a whole. + +Inside the section of the page, just before the closing tag, add the following + + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +53 + + + This CSS markup defines classes named grid, head, and so on. You could also put these style +definitions in a separate .css file and link that to the page. (In fact,you'll do that later in this +tutorial set.) But to make things easy for this tutorial, they're inside the same page that displays +the data. + +Now you can get the WebGrid helper to use these style classes. The helper has a number of +properties (for example, tableStyle) for just this purpose — you assign a CSS style class name to +them, and that class name is rendered as part of the markup that's rendered by the helper. + +Change the grid.GetHtml markup so that it now looks like this code: + +@grid.GetHtml( + tableStyle: "grid", + headerStyle: "head", + alternatingRowStyle: "alt", + columns: grid.Columns( + grid.Column("Title"), + grid.Column("Genre"), + grid.Column("Year") + ) +) + +What's new here is that you've added tableStyle, headerStyle, and alternatingRowStyle +parameters to the GetHtml method. These parameters have been set to the names of the CSS +styles that you added a moment ago. + +Run the page, and this time you see a grid that looks much less plain than before: + +To see what the GetHtml method generated, you can look at the source of the page in the +browser. We won't go into detail here, but the important point is that by specifying parameters +like tableStyle, you caused the grid to generate HTML tags like the following: + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +54 + + +
+ +The
tag has had a class attribute added to it that references one of the CSS rules that you +added earlier. This code shows you the basic pattern — different parameters for the GetHtml +method let you reference CSS classes that the method then generates along with the markup. +What you do with the CSS classes is up to you. + +Adding Paging + +As the last task for this tutorial, you'll add paging to the grid. Right now it's no problem to display +all your movies at once. But if you added hundreds of movies, the page display would get long. + +In the page code, change the line that creates the WebGrid object to the following code: + +var grid = new WebGrid(source: selectedData, rowsPerPage: 3); + +The only difference from before is that you've added a rowsPerPage parameter that's set to 3. + +Run the page. The grid displays 3 rows at a time, plus navigation links that let you page through +the movies in your database: + +Coming Up Next + +In the next tutorial, you'll learn how to use Razor and C# code to get user input in a form. You'll +add a search box to the Movies page so that you can find movies by title or genre. + +Additional Resources + +• Complete Listing for Movies Page +• + +Introduction to ASP.NET Web Programming Using the Razor Syntax + +Introducing ASP.NET Web Pages 2 + +Tutorial 3: Displaying Data + +55 + + + + + Tutorial 4: HTML Form Basics + +This tutorial shows you the basics of how to create an input form and how to handle the user's +input when you use ASP.NET Web Pages (Razor). And now that you've got a database, you'll use +your form skills to let users find specific movies in the database. + +What you'll learn: + +• How to create a form by using standard HTML elements. +• How to read the user's input in a form. +• How to create a SQL query that selectively gets data by using a search term that the user + +supplies. + +• How to have fields in the page "remember" what the user entered. + +Features/technologies discussed: + +• The Request object. +• The SQL Where clause. + +What You'll Build + +In the previous tutorial, you created a database, added data to it, and then used the WebGrid +helper to display the data. In this tutorial,you'll add a search box that lets you find movies of a +specific genre or whose title contains whatever word you enter. (For example, you'll be able to +find all movies whose genre is "Action" or whose title contains "Harry" or "Adventure.") + +When you're done with this tutorial, you'll have a page like this one: + +The listing part of the page is the same as in the last tutorial — a grid. The difference will be that +the grid will show only the movies that you searched for. + +Introducing ASP.NET Web Pages 2 + +Tutorial 4: HTML Form Basics + +56 + + + About HTML Forms + +(If you've got experience with creating HTML forms and with the difference between GET and +POST, you can skip this section.) + +A form has user input elements — text boxes, buttons, radio buttons, check boxes, drop-down +lists, and so on. Users fill in these controls or make selections and then submit the form by clicking +a button. + +The basic HTML syntax of a form is illustrated by this example: + + + +
+ + + +When this markup runs in a page, it creates a simple form that looks like this illustration: + +The element encloses HTML elements to be submitted. (An easy mistake to make is to add +elements to the page but then forget to put them inside a element. In that case, nothing is +submitted.) The method attribute tells the browser how to submit the user input. You set this to +post if you're performing an update on the server or to get if you're just fetching data from the +server. + +GET, POST, and HTTP Verb Safety + +HTTP, the protocol that browsers and servers use to exchange information, is remarkably simple +in its basic operations. Browsers use only a few verbs to make requests to servers. When you +write code for the web, it's helpful to understand these verbs and how the browser and server +use them. Far and away the most commonly used verbs are these: + +GET. The browser uses this verb to fetch something from the server. For example, when you type a +URL into your browser, the browser performs a GET operation to request the page you want. If the +page includes graphics, the browser performs additional GET operations to get the images. If the +GET operation has to pass information to the server, the information is passed as part of the URL +in the query string. + +POST. The browser sends a POST request in order to submit data to be added or changed on the +server. For example, the POST verb is used to create records in a database or change existing ones. + +Introducing ASP.NET Web Pages 2 + +Tutorial 4: HTML Form Basics + +57 + + + Most of the time, when you fill in a form and click the submit button, the browser performs a POST +operation. In a POST operation, the data being passed to the server is in the body of the page. + +An important distinction between these verbs is that a GET operation is not supposed to change +anything on the server — or to put it in a slightly more abstract way, a GET operation does not +result in a change in state on the server. You can perform a GET operation on the same resources +as many times as you like, and those resources don't change. (A GET operation is often said to be +"safe," or to use a technical term, is idempotent.) In contrast, of course, a POST request changes +something on the server each time you perform the operation. + +Two examples will help illustrate this distinction. When you perform a search using an engine like +Bing or Google, you fill in a form that consists of one text box, and then you click the search +button. The browser performs a GET operation, with the value you entered into the box passed as +part of the URL. Using a GET operation for this type of form is fine, because a search operation +doesn't change any resources on the server, it just fetches information. + +Now consider the process of ordering something online. You fill in the order details and then click +the submit button. This operation will be a POST request, because the operation will result in +changes on the server, such as a new order record, a change in your account information, and +perhaps many other changes. Unlike the GET operation, you cannot repeat your POST request — if +you did, each time you resubmitted the request, you'd generate a new order on the server. (In +cases like this, websites will often warn you not to click a submit button more than once, or will +disable the submit button so that you don't resubmit the form accidentally.) + +In the course of this tutorial, you'll use both a GET operation and a POST operation to work with +HTML forms. We'll explain in each case why the verb you use is the appropriate one. + +(To learn more about HTTP verbs, see the Method Definitions article on the W3C site.) + +Most user input elements are HTML elements. They look like , where type indicates the kind of user input control you want. These elements are +the common ones: + +• Text box: +• Check box: +• Radio button: +• Button: +• + +Submit button: + +You can also use the