Introduction
This article will explain the Razor View syntax in ASP.NET MVC. We will discuss how C# code can be written in a View combined with HTML. We can use the @ symbol to switch between C# code and HTML. If we want to define some variables and perform calculations, then we use a code block. Use @{ } to define a code block. The @ symbol is used as a code delimiter in Razor Views. However, Razor is smart enough to recognize the format of the internet email address and not to treat the @ symbol as a code delimiter.
Step 1
Open SQL Server 2014 or a version of your choice and create a table with some data.
Step 2
In Visual Studio, choose a web application project and give an appropriate name to your project.
Step 3
Select "empty template", check on the MVC checkbox, and click OK.
Step 4
Right-click on the Controllers folder and add a controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
Step 5
Right-click the Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page). Click on "Add".
Example 1
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>Razor Programming</h3>
-
- @for (int i = 1; i < 10; i++)
- {
- <b>@i</b>
- }
Example 2
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>Razor Programming</h3>
-
- @{
- int firstNumber = 10;
- int secondNumber = 20;
-
- int sum = firstNumber + secondNumber;
-
- <h4>First Number:@firstNumber</h4>
- <h4>Second Number:@secondNumber</h4>
- <h4>Total:@sum</h4>
- }
Example 3
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>Razor Programming</h3>
-
- @{
- int[]number = new int[10] {1,0,1,0,1,0,1,0,1,0};
- Array.Sort(number);
-
- foreach (var item in number)
- {
- <b>@item</b>
- }
- }
Example 4
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>Razor Programming</h3>
-
- @{
- int i, j;
- for (i = 1; i <= 5; i++)
- {
- for (j = 1; j <= i; j++)
- {
- <b>*</b>
- }
- <br/>
- }
- }
Example 5
- @{
- ViewBag.Title = "Index";
- }
-
- <h3>Razor Programming</h3>
-
- @{
- int i, j;
- for (i = 1; i <= 5; i++)
- {
- for (j = i; j < 5; j++)
- {
- <b> </b>
- }
- for (j = 1; j <= (2 * i - 1); j++)
- {
- <b>*</b>
- }
- <br />
- }
- for (i = 5; i >= 1; i--)
- {
- for (j = i; j <= 5; j++)
- {
- <b> </b>
- }
- for (j = 2; j < (2 * i - 1); j++)
- {
- <b>*</b>
- }
- <br/>
- }
- }