Sunday, 28 August 2011

ASP.NET Razor Pages

Introduction to ASP.NET Web Programming Using the Razor Syntax

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.
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>
 

OUTPUT:



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>

OUTPUT:


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 the var 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>

OUTPUT:

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>

OUTPUT:

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 a From 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>
OUTPUT:


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.

OUTPUT:



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.
  1. In your editor, create a new file and name it AddNumbers.cshtml.
  2. 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>.</p>
      <form action="" method="post">
        <p><label for="text1">First Number:</label>
          <input type="text" name="text1" />
        </p>
        <p><label for="text2">Second Number:</label>
          <input type="text" name="text2" />
        </p>
        <p><input type="submit" value="Add" /></p>
      </form>
    
      <p>@totalMessage</p>
    </body>
    </html>
    Here are some things for you to note:
    • The @ character starts the first block of code in the page, and it precedes the totalMessage variable that's embedded near the bottom of the page.
    • The block at the top of the page is enclosed in braces.
    • In the block at the top, all lines end with a semicolon.
    • The variables total, num1, num2, and totalMessage store several numbers and a string.
    • The literal string value assigned to the totalMessage variable is in double quotation marks.
    • Because the code is case-sensitive, when the totalMessage variable is used near the bottom of the page, its name must match the variable at the top exactly.
    • The expression num1.AsInt() + num2.AsInt() shows how to work with objects and methods. The AsInt method on each variable converts the string entered by a user to a number (an integer) so that you can perform arithmetic on it.
    • The <form> tag includes a method="post" attribute. This specifies that when the user clicks Add, the page will be sent to the server using the HTTP POST method. When the page is submitted, the if(IsPost) test evaluates to true and the conditional code runs, displaying the result of adding the numbers.
  3. Save the page and run it in a browser. (Make sure the page is selected in the Files workspace before you run it.) Enter two whole numbers and then click the Add button. ch02_programmingintro-7

 

No comments:

Post a Comment