ASP.NET Razor - C# Mantık Koşulları
Programlama Mantığı: Koşullara göre kodu yürütün.
Eğer Koşul
C#, koşullara göre kod yürütmenizi sağlar.
Bir koşulu test etmek için bir if ifadesi kullanırsınız . if ifadesi, testinize bağlı olarak doğru veya yanlış döndürür:
- if ifadesi bir kod bloğu başlatır
- Koşul parantez içinde yazılır
- Test doğruysa, parantez içindeki kod yürütülür.
Örnek
@{var
price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>
Başka Durum
Bir if ifadesi, else koşulu içerebilir .
else koşulu, koşulun yanlış olması durumunda yürütülecek kodu tanımlar.
Örnek
@{var
price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
Not: Yukarıdaki örnekte, ilk koşul doğruysa yürütülecektir. Diğer koşulu "diğer her şeyi" kapsar.
Else If Koşul
Birden çok koşul, else if koşuluyla test edilebilir :
Örnek
@{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>
Yukarıdaki örnekte, ilk koşul doğruysa yürütülecektir.
Değilse, bir sonraki koşul doğruysa, bu koşul yürütülür.
Koşullar varsa, herhangi bir sayıda başkasına sahip olabilirsiniz.
if ve else if koşullarından hiçbiri doğru değilse, son else bloğu (koşulsuz) "diğer her şeyi" kapsar.
Koşulları Değiştir
Bir dizi bireysel koşulu test etmek için bir anahtar bloğu kullanılabilir:
Örnek
@{
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>
Test değeri (gün) parantez içindedir. Her bir test koşulu, iki nokta üst üste ile biten bir vaka değerine ve bir break ifadesiyle biten herhangi bir sayıda kod satırına sahiptir. Test değeri durum değeriyle eşleşirse kod satırları yürütülür.
Bir anahtar bloğu, durumlardan hiçbiri doğru değilse çalışan "diğer her şey" için varsayılan bir duruma (varsayılan:) sahip olabilir.