Razor Advanced Syntax

In this article, I will explain advanced syntax in Razor. Please read my previous article Razor Syntax before reading this article, I have used project sample from article Razor Syntax .

Conditions in Razor

We can use ‘If else’ in Razor to display content based on some conditions. For example, if OrderAmount is greater than 200000 then it will take approx 10 days to deliver order items else it will take approx 5 days to deliver order items.

Below is the code using Razor ‘If else’ in CustomerDetails view:

<div class="container-fluid">
        <div class="jumbotron">
            <table class="table" style="width:400px;">
                <tr>
                    <td>Customer Id</td>
                    <td>@ViewBag.CustomerId</td>
                </tr>
                <tr>
                    <td>Customer Name</td>
                    <td>@ViewBag.CustomerName</td>
                </tr>
                <tr>
                    <td>Order Amount </td>
                    <td>@ViewBag.OrderAmount</td>
                </tr>
                <tr>
                    <td>Shipping Charges </td>
                    <td>@shippingCharges</td>
                </tr>
                <tr>
                    <td>
                        Expected delivery date of Order
                    </td>
                    <td>
                    @if (ViewBag.OrderAmount > 200000)
                     {
                     <span>@DateTime.Now.AddDays(10).ToLongDateString()</span>
                      }
                      else
                       {
                      <span>@DateTime.Now.AddDays(5).ToLongDateString()</span>
                        }
                    </td>
                </tr>
            </table>
        </div>
    </div>

Controller and action method for this view is already explained in my previous article Razor Syntax. Please see “If” syntax :

@if (ViewBag.OrderAmount > 200000)
    {
      <span>@DateTime.Now.AddDays(10).ToLongDateString()</span>
    }	

C# code and HTML is mixed together. We can write any number of ‘<span>’ tags inside “If” block. Razor is capable to distinguish between C# and HTML Code.
Press F5 and start debugging, write below URL and press enter key. You will see ‘Expected delivery date of order’ based on order amount.
http://localhost:53204/Home/CustomerDetails

Razor For Loop
We can use for loop in Razor. Below is the syntax:

<ul>
     @for(int i=0;i<6;i++)
      {
      <li> @i </li>
      }
 </ul>

For loop in razor is similar to C# for loop. It starts with @ symbol. In above example, we are displaying an unordered list for numbers 0 to 5.

Razor foreach loop
When we need to display data from an array or collection then we can use Razor foreach loop.
Now I am adding list of items which customer has ordered inside CustomerDetails() action method:

 public ActionResult CustomerDetails()
 {
  ViewBag.CustomerId = 90;
  ViewBag.CustomerName = "Anil Gupta";
  ViewBag.OrderAmount = 400000;
  ViewBag.OrderItems = new List<string>() { "AC", "TV", "Washing Machine", "Laptop" };
  return View();
  }

I have added a list of Items in ViewBag. Now I am writing foreach syntax to display it on View:

<tr>
	<td>Order Items</td>
	<td>
		<ul>
			@foreach(var item in ViewBag.OrderItems)
			{
				<li> @item</li>
			}
		</ul>
	</td>
</tr>

Press F5 and start debugging, below is the output:

Here in above code, foreach loop starts with @ symbol. This loop will iterate over OrderItems collection and print an unordered list containing items name. In each iteration , variable ‘item’ will hold an object from OrderItems collection.

Below is the complete code of Home Controller and CustomerDetails View.

HomeController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult Contact()
        {
            return View();
        }
        public ActionResult GetCustomerName(int customerid)
        {
            string customerName = string.Empty;
            var customers = new[] {
                new{ CustomerId=90,CustomerName="Ayush Kumar"},
                new{ CustomerId=91,CustomerName="Utkarsh Singh"},
                new{ CustomerId=92,CustomerName="Mohit Gupta"},
                new{ CustomerId=93,CustomerName="Akshat Kumar"}
            };

            foreach (var customer in customers)
            {
                if (customer.CustomerId == customerid)
                {
                    customerName = customer.CustomerName;
                }
            }
           return Content(customerName, "text/plain");
        }       
        public ActionResult CustomerDetails()
        {
         ViewBag.CustomerId = 90;
         ViewBag.CustomerName = "Anil Gupta";
         ViewBag.OrderAmount = 400000;
         ViewBag.OrderItems = new List<string>() { "AC", "TV", "Washing Machine", "Laptop" };
         return View();
        }

    }
}

CustomerDetails View:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-3.4.1.js"></script>
    <script src="~/Scripts/umd/popper.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
</head>
<body>
    <nav class="navbar navbar-expand-sm bg-info navbar-dark">
        <a class="navbar-brand" href="#">Logixn</a>
        <div class="col-8">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="/home/index">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/home/about">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/home/contact">Contact</a>
                </li>
            </ul>
        </div>
    </nav>
    @{ 
        decimal shippingCharges;
        if (ViewBag.OrderAmount > 200000)
        {
            shippingCharges = 0;
        }
        else
        {
            shippingCharges = 1000;
        }
    }
    <div class="container-fluid">
        <div class="jumbotron">
            <table class="table" style="width:500px;">
                <tr>
                    <td>Customer Id</td>
                    <td>@ViewBag.CustomerId</td>
                </tr>
                <tr>
                    <td>Customer Name</td>
                    <td>@ViewBag.CustomerName</td>
                </tr>
                <tr>
                    <td>Order Amount </td>
                    <td>@ViewBag.OrderAmount</td>
                </tr>
                <tr>
                    <td>Shipping Charges </td>
                    <td>@shippingCharges</td>
                </tr>
                <tr>
                    <td>
                        Expected delivery date of Order
                    </td>
                    <td>
                        @if (ViewBag.OrderAmount > 200000)
                        {
                     <span>@DateTime.Now.AddDays(10).ToLongDateString()</span>
                        }
                        else
                        {
                      <span>@DateTime.Now.AddDays(5).ToLongDateString()</span>
                        }
                    </td>
                </tr>
                <tr>
                    <td>Order Items</td>
                    <td>
                        <ul>
                            @foreach(var item in ViewBag.OrderItems)
                            {
                                <li> @item</li>
                            }
                        </ul>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>