This article is currently in the process of being translated into Persian (~33% done).
IF Statements
وقتی نشانه گذاری برای view تعریف میکنی ، خیلی کارامده که شرط هم قرار بدی که تصمیم گیری بشه قسمتی از view خوانده و render بشه یا اصلا آن قسمت از کد در view نشان داده نشه. پرکاربرد ترین شرط if است و تو میتوانی یکی از این ها را در razor استفاده کنی، درست مانند وقتی که در سی شارپ استفاده میشود. فقط کلمه کلیدی razor (@ ) رو قرار بده و شرط خودن رو بنویس
The if-statement
در اینجا یک مثال ساده از شرط if با razor آورده شده است . به خاطر داشته باشید که viewمیتواند مستقیما html معمولی شما را در داخل شرط در بر داشته باشد.
@if(DateTime.Now.Year == 2042)
{
<span>The year 2042 has finally arrived!</span>
}
As you can see, it's just C# mixed with HTML. You should be aware of two things though. First of all, in regular C#, I could have skipped the curly braces, because there's only one line of code/markup as the condition. This is not allowed in Razor though - no matter how many lines follows your control structures, they have to be surrounded by a set of curly braces. Second of all, notice how I switch directly from C# into markup. This is possible because the parser can easily understand the difference between HTML tags and C# code. On the other hand, if I had just written a line of text, without any HTML tags, the parser would have been confused. For cases like that, you can use the <text> tags, as described in the previous article.
The if-else statement
Often when there's an "if", there's also an "else" and this goes for Razor as well - you can create an if-else statement just like you would in C#. Here's an example:
@if(DateTime.Now.Year >= 2042)
{
<span>The year 2042 has finally arrived!</span>
}
else
{
<span>We're still waiting for the year of 2042...</span>
}
Summary
Using if statements in Razor is very simple, just as in C#. In combination with access to other C# language constructs like loops this makes Razor a very powerful template engine for your ASP.NET MVC pages.