Programming Tips
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:
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 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>
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 averbatim 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>
Here's the result of using both of these examples in a page:
Note Notice that 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 and that you can read or change — a text box object has a
Text
property (among others), a request object has aUrl
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 text boxes (form fields) on the page, what type of browser made the request, the URL of the page, the user identity, etc. The following example shows how to access properties of the Request
object and how to call the MapPath
method of theRequest
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 article.
The result displayed in a browser (after clicking Submit):
Quick reference about the Razor syntax.
Syntax/Sample | Razor | Web Forms Equivalent (or remarks) |
---|---|---|
Code Block | @{ int x = 123; string y = "because."; } | <% int x = 123; string y = "because."; %> |
Expression (Html Encoded) | <span>@model.Message</span> | <span><%: model.Message %></span> |
Expression (Unencoded) | <span> @Html.Raw(model.Message) </span> | <span><%= model.Message %></span> |
Combining Text and markup | @foreach(var item in items) { <span>@item.Prop</span> } | <% foreach(var item in items) { %> <span><%: item.Prop %></span> <% } %> |
Mixing code and Plain text | @if (foo) { <text>Plain Text</text> } | <% if (foo) { %> Plain Text <% } %> |
Mixing code and plain text (alternate) | @if (foo) { @:Plain Text is @bar } | Same as above |
Email Addresses | Hi philha@example.com | Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter |
Explicit Expression | <span>ISBN@(isbnNumber)</span> | In this case, we need to be explicit about the expression by using parentheses. |
Escaping the @ sign | <span>In Razor, you use the @@foo to display the value of foo</span> | @@ renders a single @ in the response. |
Server side Comment | @* This is a server side multiline comment *@ | <%-- This is a server side multiline comment --%> |
Calling generic method | @(MyClass.MyMethod<AType>()) | Use parentheses to be explicit about what the expression is. |
Creating a Razor Delegate | @{ Func<dynamic, object> b = @<strong>@item</strong>; } @b("Bold this") | Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details. |
Mixing expressions and text | Hello @title. @name. | Hello <%: title %>. <%: name %>. |
NEW IN RAZOR v2.0/ASP.NET MVC 4 | ||
Conditional attributes | <div class="@className"></div> | When
<div></div>When className = "" <div class=""></div>When className = "my-class" <div class="my-class"></div> |
Conditional attributes with other literal values | <div class="@className foo bar"> </div> | When
<div class="foo bar"></div>Notice the leading space in front of foo is removed.When className = "my-class" <div class="my-class foo bar"> </div> |
Conditional data-* attributes. data-* attributes are always rendered. | <div data-x="@xpos"></div> | When
<div data-x=""></div>When xpos = "42" <div data-x="42"></div> |
Boolean attributes | <input type="checkbox" checked="@isChecked" /> | When isChecked = true <input type="checkbox" checked="checked" /> When isChecked = false <input type="checkbox" /> |
URL Resolution with tilde | <script src="~/myscript.js"> </script> | When the app is at / <script src="/myscript.js"> </script>When running in a virtual application named MyApp <script src="/MyApp/myscript.js"> </script> |
Notice in the “mixing expressions and text” example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.
No comments:
Post a Comment