Razor Variable
As I discussed in my last article What is Razor that Razor is the combination of HTML and C#, so we can use almost all programming feature in Razor.In this article I am showing how we can work with variables. In Razor we start programming code using @.
Example of Razor Variable
Create controller name Home and view Index In this example I declared variable and calculate sum and print it.
Code of Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
int num1 = 10, num2 = 20;
int num3 = num1 + num2;
}
The sum of @num1 and @num2 is @num3
</body>
</html>
As you can see that I declared block using @ and inside this block I have declared razor variable and perform some calculation. After that closing the block I used these variables.
The output of this code as follows:-
Use of HTML code With C#
The best part of Razor is that we can put programming code with HTML in Razor.
For example:- In the above example I put all variable result in bold tag which is used to make text bold.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
int num1 = 10, num2 = 20;
int num3 = num1 + num2;
}
The sum of <b> @num1 </b> and <b>@num2</b> is <b>@num3</b>
</body>
</html>
The output of this code is as follows:-
No comments:
Post a Comment