This chapter gives you an overview of programming with ASP.NET Web Pages using the Razor syntax. ASP.NET is Microsoft's technology for running dynamic web pages on web servers.
- The top 8 programming tips for getting started with programming ASP.NET Web Pages using Razor syntax.
- Basic programming concepts you'll need for this book.
- What ASP.NET server code and the Razor syntax is all about.
The Top 8 Programming Tips
This section lists a few tips that you absolutely need to know as you start writing ASP.NET server code using the Razor syntax.
Note The Razor syntax is based on the C# programming language, and that's the language used throughout this book. However, the Razor syntax also supports the Visual Basic language, and everything you see in this book you can also do in Visual Basic. For details, see the appendixVisual Basic Language and Syntax.
You can find more details about most of these programming techniques later in the chapter.
1. You add code to a page using the @ character
The @ character starts inline expressions, single statement blocks, and multi-statement blocks:
<!-- Single statement blocks -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
This is what these statements look like when the page runs in a browser:
HTML Encoding
When you display content in a page using the @ character, as in the preceding examples, ASP.NET HTML-encodes the output. This replaces reserved HTML characters (such as < and >and &) with codes that enable the characters to be displayed as characters in a web page instead of being interpreted as HTML tags or entities. Without HTML encoding, the output from your server code might not display correctly, and could expose a page to security risks.
If your goal is to output HTML markup that renders tags as markup (for example <p></p> for a paragraph or <em></em> to emphasize text), see the section Combining Text, Markup, and Code in Code Blocks later in this chapter.
You can read more about HTML encoding in Chapter 4 - Working with Forms.
2. You enclose code blocks in braces
A code block includes one or more code statements and is enclosed in braces.
<!-- Single statement block. -->
@{ var theMonth = DateTime.Now.Month; }
<p>The numeric value of the current month: @theMonth</p>
<!-- Multi-statement block. -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<p>Today's weather: @weatherMessage</p>
The result displayed in a browser:
3. Inside a block, you end each code statement with a semicolon
Inside a code block, each complete code statement must end with a semicolon. Inline expressions don't end with a semicolon.
<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }
<!-- Multi-statement block -->
@{
var outsideTemp = 79;
var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
}
<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>
4. You use variables to store values
You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using thevar keyword. You can insert variable values directly in a page using @.
<!-- Storing a string -->
@{ var welcomeMessage = "Welcome, new members!"; }
<p>@welcomeMessage</p>
<!-- Storing a date -->
@{ var year = DateTime.Now.Year; }
<!-- Displaying a variable -->
<p>Welcome to our new members who joined in @year!</p>
The result displayed in a browser:
5. You enclose literal string values in double quotation marks
A string is a sequence of characters that are treated as text. To specify a string, you enclose it in double quotation marks:
@{ var myString = "This is a string literal"; }
If the string that you want to display contains a backslash character (\) or double quotation marks, use a verbatim string literal that's prefixed with the @ operator. (In C#, the \ character has special meaning unless you use a verbatim string literal.)
<!-- Embedding a backslash in a string -->
@{ var myFilePath = @"C:\MyFolder\"; }
<p>The path is: @myFilePath</p>
To embed double quotation marks, use a verbatim string literal and repeat the quotation marks:
<!-- Embedding double quotation marks in a string -->
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
<p>@myQuote</p>
The result displayed in a browser:
Note The @ character is used both to mark verbatim string literals in C# and to mark code in ASP.NET pages.
6. Code is case sensitive
In C#, keywords (like var, true, and if) and variable names are case sensitive. The following lines of code create two different variables, lastName and LastName.
@{
var lastName = "Smith";
var LastName = "Jones";
}
If you declare a variable as var lastName = "Smith"; and if you try to reference that variable in your page as@LastName, an error results because LastName won't be recognized.
Note In Visual Basic, keywords and variables are not case sensitive.
7. Much of your coding involves objects
An object represents 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 (database row), etc. Objects have properties that describe their characteristics — a text box object has a Text property (among others), a request object has a Url property, an email message has aFrom property, and a customer object has a FirstName property. Objects also have methods that are the "verbs" they can perform. Examples include a file object's Save method, an image object's Rotate method, and an email object's Send method.
You'll often work with the Request object, which gives you information like the values of form fields on the page (text boxes, etc.), what type of browser made the request, the URL of the page, the user identity, etc. This example shows how to access properties of the Request object and how to call the MapPath method of the Request object, which gives you the absolute path of the page on the server:
<table border="1">
<tr>
<td>Requested URL</td>
<td>Relative Path</td>
<td>Full Path</td>
<td>HTTP Request Type</td>
</tr>
<tr>
<td>@Request.Url</td>
<td>@Request.FilePath</td>
<td>@Request.MapPath(Request.FilePath)</td>
<td>@Request.RequestType</td>
</tr>
</table>
The result displayed in a browser:
8. You can write code that makes decisions
A key feature of dynamic web pages is that you can determine what to do based on conditions. The most common way to do this is with the if statement (and optional else statement).
@{
var result = "";
if(IsPost)
{
result = "This page was posted using the Submit button.";
}
else
{
result = "This was the first request for this page.";
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>
<p>@result</p>
</form>
</body>
</html>
</body>
</html>
The statement if(IsPost) is a shorthand way of writing if(IsPost == true). Along with if statements, there are a variety of ways to test conditions, repeat blocks of code, and so on, which are described later in this chapter.
The result displayed in a browser (after clicking Submit):
HTTP GET and POST Methods and the IsPost Property
The protocol used for web pages (HTTP) supports a very limited number of methods (verbs) that are used to make requests to the server. The two most common ones are GET, which is used to read a page, and POST, which is used to submit a page. In general, the first time a user requests a page, the page is requested using GET. If the user fills in a form and then clicksSubmit, the browser makes a POST request to the server.
In web programming, it's often useful to know whether a page is being requested as a GET or as a POST so that you know how to process the page. In ASP.NET Web Pages, you can use theIsPost property to see whether a request is a GET or a POST. If the request is a POST, theIsPost property will return true, and you can do things like read the values of text boxes on a form. Many examples in this book show you how to process the page differently depending on the value of IsPost.
A Simple Code Example
This procedure shows you how to create a page that illustrates basic programming techniques. In the example, you create a page that lets users enter two numbers, then it adds them and displays the result.
- In your editor, create a new file and name it AddNumbers.cshtml.
- Copy the following code and markup into the page, replacing anything already in the page.
@{
var total = 0;
var totalMessage = "";
if(IsPost) {
// Retrieve the numbers that the user entered.
var num1 = Request["text1"];
var num2 = Request["text2"];
// Convert the entered strings into integers numbers and add.
total = num1.AsInt() + num2.AsInt();
totalMessage = "Total = " + total;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add Numbers</title>
<meta charset="utf-8" />
<style type="text/css">
body {background-color: beige; font-family: Verdana, Arial;
margin: 50px; }
form {padding: 10px; border-style: solid; width: 250px;}
</style>
</head>
<body>
<p>Enter two whole numbers and then click <strong>Add</strong>.</