程式邏輯核心:根據條件動態決定程式執行路徑。掌握 VB.NET 在 Razor 中的語法特性,撰寫清晰可維護的伺服器端邏輯。
VB.NET 使用 If...Then...End If 結構進行條件判斷,語法特點:
@Code
Dim price = 50
End Code
<html>
<body>
@If price > 30 Then
@<p>The price is too high.</p>
End If
</body>
</html>
Else 子句定義條件為 False 時的執行路徑,確保程式邏輯完整覆蓋所有可能情況:
@Code
Dim price = 20
End Code
<html>
<body>
@If price > 30 Then
@<p>The price is too high.</p>
Else
@<p>The price is OK.</p>
End If
</body>
</html>
注意: Else 條件涵蓋除 If 條件外的「所有其他情況」,確保邏輯無死角。
多重條件判斷使用 ElseIf 建立階層式決策樹:
@Code
Dim price = 25
End Code
<html>
<body>
@If price >= 30 Then
@<p>The price is high.</p>
ElseIf price > 20 And price < 30 Then
@<p>The price is OK.</p>
Else
@<p>The price is low.</p>
End If
</body>
</html>
執行優先順序:首個符合條件的區塊執行,後續條件不再評估。ElseIf 數量無限制。若所有 If/ElseIf 均不符合,最終 Else 區塊 (無條件) 執行。
Select Case 結構適用於單一變數對多個離散值的匹配場景,程式碼結構更清晰:
@Code
Dim weekday = DateTime.Now.DayOfWeek
Dim day = weekday.ToString()
Dim message = ""
End Code
<html>
<body>
@Select Case day
Case "Monday"
message = "This is the first weekday."
Case "Thursday"
message = "Only one day before weekend."
Case "Friday"
message = "Tomorrow is weekend!"
Case Else
message = "Today is " & day
End Select
<p>@message</p>
</body>
</html>
Select Case 後緊接測試變數 (day)。每個 Case 標籤對應一個匹配值與任意行程式碼。測試值與 Case 值匹配時執行對應程式碼。Case Else 為預設情況,涵蓋所有未明確列出的值。
| 特性 | VB.NET | C# |
|---|---|---|
| 程式碼區塊 | @Code ... End Code | @{ ... } |
| 內嵌運算式 | @variable | @variable |
| 字串串接 | & 運算子 | + 運算子 |
| 大小寫敏感 | 不區分 | 區分 |
| 檔案副檔名 | .vbhtml | .cshtml |
| 變數宣告 | Dim | var / 型別 |