ASP.NET Web Pages - w3schools note - Razor-Markup

Syntax Rules (语法规则)

语法与phpASP类似,主要用于将 (C#VB) 嵌入到 ASP.NET 的网页中

相关语法 (C#):

@{}, {}内用来写C#相关的程式码
如:@{ var myMessage = "Hello World"; }

透过在变数名称前面加上@来呼叫变数
如:@myMessage
以及:<p>The value of myMessage is: @myMessage</p>
这样最后就会显示The value of myMessage is: Hello World

C# 语法的末端以 ; 结尾

变数型别的宣告和 C# 语法 一样

字串的话就必须要有引号括号起来,如:"Hey!"

C#的副档名为 .cshtml

更多範例:

@{ var greeting = "Welcome to our site!";`var weekDay = DateTime.Now.DayOfWeek;`var greetingMessage = greeting + " Today is: " + weekDay;`}<p>The greeting is: @greetingMessage</p>

Variable (变数)

// Using the var keyword:var greeting = "Welcome to W3Schools";var counter = 103;var today = DateTime.Today;// Using data types:string greeting = "Welcome to W3Schools";int counter = 103;DateTime today = DateTime.Today;

之前看过有文章提到,通常还是会给出确切的资料型别
变数型别和 Java 类似,不过有些改成小写,有些字母数比较少
如:stringbool

在运算子的部分和Java几乎一样,转换资料型别的方法就直接看原文就好

Loops (迴圈)

语法的部分直接阅读应该可以看得懂

<html><body>@for(var i = 10; i < 21; i++)    {<p>Line @i</p>}</body></html>

如果使用CollectionArray,通常会使用 foreach 迴圈。

<html><body><ul>@foreach (var x in Request.ServerVariables)    {<li>@x</li>}</ul></body></html>

While Loops (While 迴圈)

<html><body>@{var i = 0;while (i < 5)    {    i += 1;    <p>Line @i</p>    }}</body></html>

Arrays (阵列)

@{string[] members = {"Jani", "Hege", "Kai", "Jim"};int i = Array.IndexOf(members, "Kai")+1;int len = members.Length;string x = members[2-1];}<html><body><h3>Members</h3>@foreach (var person in members){<p>@person</p>}<p>The number of names in Members are @len</p><p>The person at position 2 is @x</p><p>Kai is now in position @i</p></body></html>

逻辑条件判断

这边直接整合在一起好了...

If Condition@{var price=50;}<html><body>@if (price>30)    {    <p>The price is too high.</p>    }</body></html>Else Condition@{var price=20;}<html><body>@if (price>30)  {  <p>The price is too high.</p>  }else  {  <p>The price is OK.</p>  }</body></html>Else If Condition@{var price=25;}<html><body>@if (price>=30)  {  <p>The price is high.</p>  }else if (price>20 && price<30)  {  <p>The price is OK.</p>  }else  {  <p>The price is low.</p>  }   </body></html>

Switch Conditions

@{var weekday=DateTime.Now.DayOfWeek;var day=weekday.ToString();var message="";}<html><body>@switch(day){case "Monday":    message="This is the first weekday.";    break;case "Thursday":    message="Only one day before weekend.";    break;case "Friday":    message="Tomorrow is weekend!";    break;default:    message="Today is " + day;    break;}<p>@message</p></body></html>

笔记来源:ASP.NET Web Pages - Adding Razor Code、ASP.NET Razor - C# Variables、


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章