在页面里用@字符加C#代码。@开始一个内联表达式,可以包括单行语句或多行语句。如:
< !-- 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>
代码块用大括号包起来,代码块中的每个语句用分号结束。
定义变量并在页面中使用。
字符串中的转义字符,在字符串前面加@
@{ var myFilePath = @"C:MyFolder"; }
< p>The path is: @myFilePath</p>
双写双引号可以在页中显示双引号
@{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
< p>@myQuote</p>
代码大小写敏感
在页的代码中仍然可以使用对象,如request:
< 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>
可以在页中加上判断逻辑,比如在cshtml中加入以下代码:
Get:读一个页 post:提交一个页
@{
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>
简单计算器的实现:
1 创建一个页面,名为AddNumbers.cshtml
2 拷贝以下代码,覆盖页中的内容:
注意:网站,右键,属性,不打开页。启动时在asp.net development server上右键,在浏览器中浏览。在不改控制器的情况下,应覆盖Index.cshtml.
@{
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; 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>
Razor引擎的页包含客户端内容(html,css,js,文本。。。)和服务器端内容(c#,vb.net)。服务器端内容可以生成客户端内容。页后缀是cshtml或vbhtml
Razor引擎语法详解:
用@:运算符输出单行内容,包括一般文本和未匹配的HTML以及服务器代码变量:
@if(IsPost) {
// Plain text followed by an unmatched HTML tag and server code.
@: The time is: <br /> @DateTime.Now
// Server code and then plain text, matched tags, and more text.
@DateTime.Now @:is the <em>current</em> time.
}
如果是多行,则每行都应有@: 或用<text></text>括起来
@if(IsPost) {
// Repeat the previous example, but use <text> tags.
<text>
The time is: <br /> @DateTime.Now
@DateTime.Now is the <em>current</em> time.
</text>
}
@{
var minTemp = 75;
<text>It is the month of @DateTime.Now.ToString("MMMM"), and
it's a <em>great</em> day! <br /><p>You can go swimming if it's at
least @minTemp degrees. </p></text>
}
多余的空格在语句中是不影响的,比如:
@{ var lastName = "Smith"; }写法正确。
为提高可读性断句也是允许的,比如下面写法正确:
@{ var theName =
"Smith"; }
@{
var
personName
=
"Smith"
;
}
但是字符串常量中间不能断开:
@{ var test = "This is a long
string"; } // Does not work!错误!
如果这样写,就对了:
@{ var longString = @"This is a
long
string";
}
注释,RAZOR注释,@*……*@,比如:
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
在服务器代码中,仍然可以用c#注释:
@{
// This is a comment.
var myVar = 17;
/* This is a multi-line comment
that uses C# commenting syntax. */
}
以下是HTML注释,HTML注释可以连HTML标记一起注释掉,HTML注释会被发往浏览器,查看源代码时会被看到:
< !-- This is a comment. -->
< !-- <p>This is my paragraph.</p> -->
声明和使用变量:
@{
// Assigning a string to a variable.
var greeting = "Welcome!";
// Assigning a number to a variable.
var theCount = 3;
// Assigning an expression to a variable.
var monthlyTotal = theCount + 5;
// Assigning a date value to a variable.
var today = DateTime.Today;
// Assigning the current page's URL to a variable.
var myPath = this.Request.Url;
// Declaring variables using explicit data types.
string name = "Joe";
int count = 5;
DateTime tomorrow = DateTime.Now.AddDays(1);
}
使用上面声明的变量:
@{
// Embedding the value of a variable into HTML markup.
<p>@greeting, friends!</p>
// Using variables as part of an inline expression.
<p>The predicted annual total is: @( monthlyTotal * 12)</p>
// Displaying the page URL with a variable.
<p>The URL to this page is: @myPath</p>
}
数据类型转换:
@{
var total = 0;
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();
}
}
以上将字符串转换成数字
var myIntNumber = 0;
var myStringNum = "539";
if(myStringNum.IsInt()==true){
myIntNumber = myStringNum.AsInt();
}
AsBool(),IsBool() AsFloat(), IsFloat() AsDecimal(), IsDecimal()
AsDateTime(), IsDateTime() ToString()
var myStringBool = "True";
var myVar = myStringBool.AsBool();
关于运算符大多跟c#相同,示例:
@(5 + 13)
@{ var netWorth = 150000; }
@{ var newTotal = netWorth * 2; }
@(newTotal / 2)
用~获取虚拟根路径:
@{
var myImagesFolder = "~/images";
var myStyleSheet = "~/styles/StyleSheet.css";
}
将虚拟路径转换为绝对路径:
@{
var dataFilePath = "~/dataFile.txt";
}
< !-- Displays a physical path C:WebsitesMyWebSitedatafile.txt -->
<p>@Server.MapPath(dataFilePath)</p>
用Href方法将路径转换成浏览器能识别的路径(~是不被浏览器识别的):
@{
var myImagesFolder = "~/images";
var myStyleSheet = "~/styles/StyleSheet.css";
}
< !-- This code creates the path "../images/Logo.jpg" in the src attribute. -->
<img src="@Href(myImagesFolder)/Logo.jpg" />
< !-- This produces the same result, using a path with ~ -->
<img src="@Href("~/images")/Logo.jpg" />
< !-- This creates a link to the CSS file. -->
<link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" />
If语句:
@{
var showToday = false;
if(showToday)
{
@DateTime.Today;
}
else
{
<text>Sorry!</text>
}
}
@{
var theBalance = 4.99;
if(theBalance == 0)
{
<p>You have a zero balance.</p>
}
else if (theBalance > 0 && theBalance <= 5)
{
<p>Your balance of $@theBalance is very low.</p>
}
else
{
<p>Your balance is: $@theBalance</p>
}
}
Switch语句:
@{
var weekday = "Wednesday";
var greeting = "";
switch(weekday)
{
case "Monday":
greeting = "Ok, it's a marvelous Monday";
break;
case "Tuesday":
greeting = "It's a tremendous Tuesday";
break;
case "Wednesday":
greeting = "Wild Wednesday is here!";
break;
default:
greeting = "It's some other day, oh well.";
break;
}
<p>Since it is @weekday, the message for today is: @greeting</p>
}
循环语句:
@for(var i = 10; i < 21; i++)
{
<p>Line #: @i</p>
}
< ul>
@foreach (var myItem in Request.ServerVariables)
{
<li>@myItem</li>
}
< /ul>
@{
var countNum = 0;
while (countNum < 50)
{
countNum += 1;
<p>Line #@countNum: </p>
}
}
内置对象response,request,都有智能提示:
@{
// Access the page's Request object to retrieve the Url.
var pageUrl = this.Request.Url;
}
< a href="@pageUrl">My page</a>
集合对象:
@* Array block 1: Declaring a new array using braces. *@
@{
<h3>Team Members</h3>
string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
@{
string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
<p>The number of names in the teamMembers array: @teamMembers.Length </p>
<p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
<p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
<h3>Current order of team members in the list</h3>
foreach (var name in teamMembers)
{
<p>@name</p>
}
<h3>Reversed order of team members in the list</h3>
Array.Reverse(teamMembers);
foreach (var reversedItem in teamMembers)
{
<p>@reversedItem</p>
}
}
Directory用键值对存取:
@{
var myScores = new Dictionary<string, int>();
myScores.Add("test1", 71);
myScores.Add("test2", 82);
myScores.Add("test3", 100);
myScores.Add("test4", 59);
}
< p>My score on test 3 is: @myScores["test3"]%</p>
@(myScores["test4"] = 79)
< p>My corrected score on test 4 is: @myScores["test4"]%</p>
Razor有2种向方法传递参数的方式,固定位置(严格按照声明的参数去传递,位置都不能错)和命名(一般在有多个参数时使用,可以改变参数位置,增强可读性,但是必须指定参数名):
固定位置:
// Pass parameters to a method using positional parameters.
var myPathPositional = Request.MapPath("/scripts", "/", true);
< p>@myPathPositional</p>
命名:
// Pass parameters to a method using named parameters.
var myPathNamed = Request.MapPath(baseVirtualDir: "/", allowCrossAppMapping: true, virtualPath: "/scripts");
< p>@myPathNamed</p>
异常捕捉:
@{
var dataFilePath = "~/dataFile.txt";
var fileContents = "";
var physicalPath = Server.MapPath(dataFilePath);
var userMessage = "Hello world, the time is " + DateTime.Now;
var userErrMsg = "";
var errMsg = "";
if(IsPost)
{
// When the user clicks the "Open File" button and posts
// the page, try to open the created file for reading.
try {
// This code fails because of faulty path to the file.
fileContents = File.ReadAllText(@"c:batafile.txt");
// This code works. To eliminate error on page,
// comment the above line of code and uncomment this one.
//fileContents = File.ReadAllText(physicalPath);
}
catch (FileNotFoundException ex) {
// You can use the exception object for debugging, logging, etc.
errMsg = ex.Message;
// Create a friendly error message for users.
userErrMsg = "A file could not be opened, please contact "
+ "your system administrator.";
}
catch (DirectoryNotFoundException ex) {
// Similar to previous exception.
errMsg = ex.Message;
userErrMsg = "A directory was not found, please contact "
+ "your system administrator.";
}
}
else
{
// The first time the page is requested, create the text file.
File.WriteAllText(physicalPath, userMessage);
}
}
< !DOCTYPE html>
< html lang="en">
<head>
<meta charset="utf-8" />
<title>Try-Catch Statements</title>
</head>
<body>
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Open File"/>
</form>
<p>@fileContents</p>
<p>@userErrMsg</p>
</body>
< /html>