ASP.NET Razor - VB 逻辑条件

编程逻辑:执行基于条件的代码。

If 条件

VB 允许您执行基于条件的代码。

如需测试某个条件,您可以使用 if 语句。if 语句会基于您的测试来返回 true 或 false:

  • if 语句启动代码块
  • 条件位于 if 和 then 之间
  • 如果条件为真,则执行 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 条件

if 语句能够包含 else 条件

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>
</htmlV>

تشغيل مثال

注释:在上面的例子中,如果价格不大于 30,则执行其余的语句。

ElseIf 条件

可通过 else if 条件来测试多个条件:

مثال

@Code
Dim price=25
End Code
<html>
<body>
@If price>=30 Then
    @<p>The price is high.</p>
ElseIf price>20 And price<30 
    @<p>The price is OK.</p>
Else
    @<p>The price is low.</p>
End If    
</body>
</html>

تشغيل مثال

في المثال السابق، إذا كانت الشروط الأولى صحيحة، یتم تنفيذ الكود الأول.

إذا لم تكن الشروط الأولى صحيحة، یتم تنفيذ الكود الثاني.

يمكنك تعيين أي عدد من شروط else if.

إذا لم تكن الشروط if و else if صحيحة، یتم تنفيذ آخر كود else.

شرط Select

كود selectيمكن استخدامها لتجربة سلسلة من الشروط المحددة:

مثال

@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، یتم تنفيذ سطور الكود.

يمكن استخدام كود select لضبط الحالة الافتراضية للجميع حالات (default:)، مما یسمح بتنفيذ الكود عندما لا تكون جميع الحالات صحيحة.