How to use Razor View Engine in ASP.NET Core

By FoxLearn 2/3/2025 9:14:14 AM   58
The ASPX View Engine, a legacy feature in ASP.NET MVC, was part of the framework from its early days.

Over time, the Razor View Engine has emerged as the more advanced option, now serving as the default view engine in ASP.NET Core MVC. This article briefly compares both view engines and shows you how to use Razor in ASP.NET Core MVC.

What Is a View Engine?

A view engine is responsible for transforming a server-side template into HTML markup and rendering it in a web browser when a controller’s action method triggers it. ASP.NET MVC initially used the ASPX View Engine, but Razor was introduced in later versions. Razor is now the default view engine for ASP.NET Core MVC applications.

The ASPX View Engine is part of the System.Web.Mvc.WebFormViewEngine namespace, whereas Razor can be found in the Microsoft.AspNetCore.Mvc.Razor namespace.

How Does a View Engine Work?

Each view engine has three key components: the ViewEngine class, the View class, and the template parser. The ViewEngine class, which extends the IViewEngine interface, is responsible for locating view templates. The View class, which extends the IView interface, combines the template with data and converts it to HTML. The template parser compiles the view into executable code.

If needed, you can create your own custom view engine in ASP.NET Core. You would build a class that extends the IView and IViewEngine interfaces from the Microsoft.AspNetCore.Mvc.ViewEngines namespace. You’d then implement the GetView and FindView methods from IViewEngine, and the RenderAsync method from IView to handle runtime view rendering.

Creating a Razor View in ASP.NET Core MVC

To demonstrate how to create a simple view in a new ASP.NET Core MVC application, modify the HomeController.cs file as follows:

public IActionResult Welcome(){
    ViewData["Message"] = "Hello from Razor!";
    return View();
}

Next, create a new Razor view file named Welcome.cshtml inside the Views/Home folder with this code:

@ViewData["Message"]

Removing Default View Engines in ASP.NET Core MVC

If you want to use a custom view engine, you might need to remove the default Razor and ASPX view engines. You can do this by modifying the ConfigureServices method in your Startup.cs file:

services.AddMvc()
        .AddViewOptions(options =>
        {
            options.ViewEngines.Clear();
            options.ViewEngines.Add(typeof(MyCustomViewEngine));
        });

Using Conditional Logic in Razor View Engine

Razor allows you to use standard programming constructs like if, else if, and switch for conditional rendering. Here’s an example of an if statement:

@{
    var x = 10;
}
<html>
    <body>
        @if (x > 6)
        {
            <p>The value of x is greater than 6.</p>
        }
    </body>
</html>

An if-else statement would look like this:

@{
    var x = 2;
}
<html>
    <body>
        @if (x > 6)
        {
            <p>The value of x is greater than 6.</p>
        }
        else
        {
            <p>The value of x is less than 6.</p>
        }
    </body>
</html>

Switch Case in Razor View Engine

For a more advanced conditional check, you can use a switch statement in Razor. Here's an example:

@{
    var weekday = DateTime.Now.DayOfWeek.ToString();
    var text = string.Empty;
}
<html>
    <body>
        @switch(weekday)
        {
            case "Monday":
                text = "Today is Monday, the first working day.";
                break;
            case "Friday":
                text = "Today is Friday, the last working day.";
                break;
            default:
                text = "Today is: " + weekday;
                break;
        }
        @text
    </body>
</html>

Using Loops in Razor View Engine

You can use loops in Razor views to handle repetitive tasks.

Here’s an example using a for loop to display numbers from 1 to 10:

<html>
    <body>
        <p>Displaying numbers 1 to 10:</p>
        @for (var i = 1; i <= 10; i++)
        {
            <p>@i</p>
        }
    </body>
</html>

Similarly, you can use a foreach loop to display elements from a collection.

For example, to display all keys from the Request.Headers collection:

<html>
    <body>
        <ul>
            @foreach (var header in this.Context.Request.Headers)
            {
                <li>@header.Key</li>
            }
        </ul>
    </body>
</html>

Using Models in Razor Views

To pass data to a Razor view, you can define a model class and bind it in the view.

Here’s an example of a model class:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Then, in your Razor view, you can reference this model:

@model Customer
<ul>
    <li>Customer Id: @Model.Id</li>
    <li>First Name: @Model.FirstName</li>
    <li>Last Name: @Model.LastName</li>
</ul>

Razor is a powerful and flexible templating engine for ASP.NET Core MVC. It provides a concise, readable syntax for generating dynamic HTML from server-side templates. With its ability to support common programming constructs, loops, and models, Razor simplifies the development of interactive web applications.