iT邦幫忙

0

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

  • 分享至 

  • xImage
  •  

Syntax Rules (語法規則)

語法與phpASP類似,主要用於將 (C#VB) 嵌入到 ASP.NET 的網頁中

相關語法 (C#):

  1. @{}, {}內用來寫C#相關的程式碼
    如:@{ var myMessage = "Hello World"; }

  2. 透過在變數名稱前面加上@來呼叫變數
    如:@myMessage
    以及:<p>The value of myMessage is: @myMessage</p>
    這樣最後就會顯示The value of myMessage is: Hello World

  3. C# 語法的末端以 ; 結尾

  4. 變數型別的宣告和 C# 語法 一樣

  5. 字串的話就必須要有引號括號起來,如:"Hey!"

  6. 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 CodeASP.NET Razor - C# Variables


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言