Introduction
In my last article I discussed how we can use programming statement in Razor. In my last article we declared some variable and perform some calculation on it. In this tutorial I am going to discuss how we can use if-else statement and looping.
If-else in Razor
As we declared variable using @, similarly we can declare if else statement using @
Note: - I am taking previous article code as an example. If you are directly reading it then kindly go through last article first.
For example:-
In this example I am taking two numbers and calculating the difference between them.
In this example I am taking two numbers and calculating the difference between them.
Code of Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
int num1 = 18, num2 = 107;
int num3;
}
@if (num1 > num2)
{
num3 = num1 - num2;
}
else
{
num3 = num2 - num1;
}
The difference between <b> @num1</b> and <b>@num2</b> is <b>@num3</b>
</body>
</html>
Now execute this code
Looping in Razor
As we used if else statement in Razor, similarly we can use looping in it.
For example:-
In this example I am printing the counting from 1 to 10 in ul html tag. As we already discussed that we can use html tag with out code.
In this example I am printing the counting from 1 to 10 in ul html tag. As we already discussed that we can use html tag with out code.
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Loop Example<br /><br />
printing counting 1 to 10
<br />
@for (int i = 1; i <= 10; i++)
{
<ul>
<li>@i</li>
</ul>
}
</body>
</html>
The output of this code will be as follows:-
Similarly we can use while and do-while loop.
No comments:
Post a Comment