ASP.NET Razor - VB 邏輯條件


編程邏輯:根據(jù)條件執(zhí)行代碼。


If 條件

VB 允許根據(jù)條件執(zhí)行代碼。

使用 if 語(yǔ)句來(lái)判斷條件。根據(jù)判斷結(jié)果,if 語(yǔ)句返回 true 或者 false:

  • if 語(yǔ)句開(kāi)始一個(gè)代碼塊
  • 條件寫(xiě)在 if 和 then 之間
  • 如果條件為真,if ... then 和 end if 之間的代碼被執(zhí)行

實(shí)例

@Code
Dim price=50
End Code
<html>
<body>
@If price>30 Then
@<p>The price is too high.</p>
End If
</body>
</html>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例


Else 條件

if 語(yǔ)句可以包含 else 條件

else 條件定義了當(dāng)條件為假時(shí)被執(zhí)行的代碼。

實(shí)例

@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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例

注釋?zhuān)?/strong>在上面的實(shí)例中,如果第一個(gè)條件為真,if 塊的代碼將會(huì)被執(zhí)行。else 條件覆蓋了除 if 條件之外的"其他所有情況"。


ElseIf 條件

多個(gè)條件判斷可以使用 elseif 條件

實(shí)例

@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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例

在上面的實(shí)例中,如果第一個(gè)條件為真,if 塊的代碼將會(huì)被執(zhí)行。

如果第一個(gè)條件不為真且第二個(gè)條件為真,elseif 塊的代碼將會(huì)被執(zhí)行。

elseif 條件的數(shù)量不受限制。

如果 if 和 elseif 條件都不為真,最后的 else 塊(不帶條件)覆蓋了"其他所有情況"。


Select 條件

select 塊可以用來(lái)測(cè)試一些單獨(dú)的條件:

實(shí)例

@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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線(xiàn)實(shí)例

"Select Case" 后面緊跟著測(cè)試值(day)。每個(gè)單獨(dú)的測(cè)試條件都有一個(gè) case 值和任意數(shù)量的代碼行。如果測(cè)試值與 case 值相匹配,相應(yīng)的代碼行被執(zhí)行。

select 塊有一個(gè)默認(rèn)的情況(Case Else),當(dāng)所有的指定的情況都不匹配時(shí),它覆蓋了"其他所有情況"。