RAZOR 存在ASP.net 框架中,可以将服务器代码混合在html中使用。
文件名: *.cshtml, *.vbhtml
1.定义变量,使用变量(单行定义变量)
单行定义变量
@{var total=7;} @{var message = "欢迎到来";} @{var CurrentTime = DateTime.Now.ToString();} <br /><br /><br /><br /> total 的value 是 @total <br /> message value is @message<br /> 当前时间是 @CurrentTime
多行定义变量
@{var total = 7; var message = "欢迎到来"; var CurrentTime = DateTime.Now.ToString(); }
2. 转移字符 “
@{var myFilePath = @"c:MyFolder";} @{var myQuote = "he said:"我非常高兴"";} @{var myQuote2 = @"he said:""我非常高兴""";} <p> the path is @myFilePath </p> <p>@myQuote</p> <p>@myQuote2</p>
3. 对大小写敏感
@{ var lastName = "Smith"; var LastName = "Jones"; } <p> @lastName @LastName </p>
4. 使用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>
5. if.. else 代码结合,判断是get 还是post请求页面
@{ var result = ""; if(IsPost) { result = "post 请求"; } else { result = "get请求"; } } <form method="post" > <input type="submit" name="Submit" value="Submit" /> <p>@result</p> </form>
var result =0; //必须初始化;然后编译器根据初始化的值 判断其类型
6. if.else 根据post的值实现相加计算出结果
@{ var result =0; var reulstMessage = ""; if(IsPost) { result = Request["text1"].AsInt() + Request["text2"].AsInt(); reulstMessage = "相加的结果为:" + result; } } @*//action不填写也没事*@ <form method="post" action=""> <p> <label for="text1">数1</label> <input type="text" name="text1"/> </p> <p> <label for="text2">数2</label> <input type="text" name="text2" /> </p> <p> <input type="submit" value="相加" name="Submit" /> </p> <p> @Html.Label("结果","result") @Html.TextBox("result",@reulstMessage) </p> </form>
7. @: 输出字符串 ,以及 <text>…</text>输出多行
@{ if(IsPost) { } else { @: The time is @DateTime.Now <br /> @DateTime.Now @: is the time <br /> <text> The time is: <br /> @DateTime.Now <br /><br /></text> } }
注意:@:后面有空格
8. Whitespace 对定义变量的影响
@{var a=”345”;} @{var a= “345”;}
@{var a
=”356”;}
但是值不能换行
@{var a=”34
5”;} //错误的
9.注释
@{ //注释1 /*注释 * 2*/ @*注释3*@ }
10. var 变量类型,大多数时候都可以这样用。 有时候要强类型化比如 DateTime。 另外:@(total * 12)计算乘号
@{ Layout = "~/_SiteLayout.cshtml"; } @{ // 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> } @*//action不填写也没事*@
11.操作符,类型转化,类型检测
AsInt(),IsInt()
AsBool(),IsBool()
AsFloat(),IsFloat()
AsDecimal(),IsDecimal()
AsDateTime(),IsDateTime()
ToString()
操作符,+ – */ == ,+=,-=,=,.,(),[],!,&& ||
@( 5+13)
@{var value1=150000;}
@{var value2=value1*2}
@(value2 / 2 )
12. 虚拟路径( / ),物理路径( )
Server.MapPath 虚拟路径转换为物理路径 // ~标明虚拟路径
@{ var dataFilePath = "~/dataFile.txt"; } <!-- Displays a physical path C:WebsitesMyWebSitedatafile.txt --> <p>@Server.MapPath(dataFilePath)</p>
12.循环体
@for(var i = 10; i < 21; i++) { <p>Line #: @i</p> }
@{ var countNum = 0; while (countNum < 50) { countNum += 1; <p>Line #@countNum: </p> } }
<ul> @foreach (var myItem in Request.ServerVariables) { <li>@myItem</li> } </ul>
集合对象(ARRAY 和DIcitory )
1)数组操作
@* 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> } }
array indexof方法确定元素位置,反转数组输出
@{ 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> } }
2)字典操作
字典存放分数,查看课程为test3的分数;并把课程为test4的分数设置为0
@{ var myScores = new Dictionary<string, int>(); myScores.Add("test1", 71); myScores.Add("test2",72); myScores.Add("test3",73); myScores.Add("test4", 74); } <p>test3 score is @myScores["test3"]</p> //给test4 赋值为0 @(myScores["test4"]=0) <p>test4 score is @myScores["test4"]</p>
13。 try catch (Handling Errors)
例子:读取的文件不存在,提示错误
@{ 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:atafile.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>