Wednesday, June 2, 2021

MVC Razor Syntax Explanations using Examples

Razor Syntax in View


using System.Web.Mvc;
namespace WebRazorSyntax.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}
Index.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        Razor expression inside HTML tag
        <h2>@DateTime.Now</h2>
        C# statements inside Razor @@block
        @{ 
            int number1 = 20;
            int number2 = 29;
            int sum = number1 + number2;
        }
    <h4>Number1 = @number1</h4>
    <h4>Number2 = @number2</h4>
    <h4>Sum of numbers: @sum</h4>
    @{ string msg;}
    @if (number1>number2)
    {
        msg ="number1 > number2";
    }
    else
    {
        msg = "number1 < number2";
    }
    <h4>@msg</h4>
    </div>
</body>
</html>

OUTPUT


No comments:

Post a Comment

Hot Topics