How to use Razor View Engine in ASP.NET Core MVC

The ASPX View Engine is the legacy view engine constructed into ASP.Web MVC from its original times. The Razor View Engine is extra innovative and is now the default view engine of ASP.Web Main MVC. This posting compares these two view engines in quick and then discusses how you can do the job with the Razor View Engine in ASP.Web Main MVC.

To do the job with the code illustrations delivered in this posting, you need to have Visual Studio 2019 put in in your program. If you do not now have a copy, you can obtain Visual Studio 2019 right here.

Make an ASP.Web Main MVC undertaking in Visual Studio

Very first off, let us produce an ASP.Web Main undertaking in Visual Studio 2019. Subsequent these methods will produce a new ASP.Web Main MVC 5 undertaking in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Simply click on “Create new undertaking.”
  3. In the “Create new project” window, pick “ASP.Web Main Net App (Product-View-Controller)” from the checklist of templates displayed.
  4. Simply click Next.
  5. In the “Configure your new project” window, specify the title and spot for the new undertaking.
  6. Optionally examine the “Place alternative and undertaking in the exact same directory” examine box, based on your preferences.
  7. Simply click Next.
  8. In the “Additional Information” window demonstrated upcoming, pick .Web 5. as the target framework from the drop-down checklist at the prime. Go away the “Authentication Type” as “None” (default).
  9. Assure that the examine packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we will not be applying any of these functions right here.
  10. Simply click Make.

A new ASP.Web Main MVC 5 undertaking will be created. We’ll use this undertaking to do the job with Razor sights in the subsequent sections of this posting.

What is a view engine?

A view engine interprets a server-aspect template into HTML markup and renders it in the net browser when activated by a controller’s action technique. ASP.Web MVC originally transported with the ASPX View Engine, but the Razor View Engine was additional in afterwards variations. The Razor View Engine is now the default view engine for ASP.Web Main MVC purposes.

Although the ASPX View Engine is accessible as element of the Technique.Net.Mvc.WebFormViewEngine namespace, the Razor View Engine is accessible in the Microsoft.AspNetCore.Mvc.Razor namespace.

How does a view engine do the job?

Every single view engine contains 3 parts: the ViewEngine course, the view course, and the template parser. The ViewEngine course extends the IViewEngine interface and implements its users. This course is responsible for locating view templates. The view course extends the IView interface and implements its users. This course is responsible for combining the template with information and then converting it to HTML markup to be rendered in the net browser. The template parser is a parsing engine that compiles the view into executable code.

You can also produce your possess tailor made view engine in ASP.Web Main. To do this, you produce a course that extends the IView and the IViewEngine interfaces pertaining to the Microsoft.AspNetCore.Mvc.ViewEngines namespace. You then apply the two approaches of the IViewEngine interface, particularly GetView and FindView. You also apply the RenderAsync technique of the IView interface. This technique is responsible for rendering the view engine at runtime.

Make a new Razor view in ASP.Web Main MVC

In the new ASP.Web Main MVC software we created above, let us produce a easy view. To do this, edit the HomeController.cs file and include the subsequent code:

community IActionResult Welcome()
    ViewData["Information"] = "Howdy Entire world!"
    return View()

Next, produce a new view file named Welcome.cshtml in the Views/Dwelling folder and enter the subsequent code:

@ViewData["Information"]

Remove the default view engines in ASP.Web Main MVC

When you produce a tailor made view engine, you may often want to eliminate the default view engines. You can eliminate each the Razor View Engine and the ASPX View Engine and then include your possess tailor made view engine as demonstrated in the code snippet specified beneath.

products and services.AddMvc()
            .AddViewOptions(possibilities =>
           
                possibilities.ViewEngines.Apparent()
                possibilities.ViewEngines.Insert(typeof(MyCustomViewEngine))
            )

Use an if construct in Razor View Engine

In this portion we’ll look at how we can system our view applying the Razor syntax. Let’s initially use some popular constructs these types of as the if, if else, and switch circumstance statements.

The subsequent code snippet illustrates how you can use an if statement in Razor.

    @var x = ten 
     
        
          @if (x > 5) 
            
             

The value of x is increased than 5.

 
            
        
   

The upcoming code snippet exhibits how you can use an if else statement in Razor.

    @var x = two 
     
        
          @if (x > 5) 
            
             

The value of x is increased than 5.

 
            
           else 
            
             

The value of x is much less than 5.

 
             
        
   

Use a switch circumstance statement in Razor View Engine

In this article is how you can use a switch circumstance statement in Razor.

@
var weekday=DateTime.Now.DayOfWeek.ToString()
var text=string.Empty



@switch(weekday)

circumstance "Monday":
    text="This is the initially performing working day of the 7 days."
    split
circumstance "Friday":
    text="This is the previous performing working day of the 7 days"
    split
default:
    text="Currently is: " + weekday
    split

@text



If the working day is a Monday, when you operate the software you would see the subsequent output in your net browser.

razor views aspnet core IDG

Figure 1. Razor sights in action!

Use loops in Razor View Engine

You can use loops in your Razor sights to perform repetitive actions. The subsequent code snippet illustrates how you can do the job with loops in Razor.

 
 
    

Displaying quantities 1 to ten


          @for(var i = 1 i <= 10 i++) 
                         
             

@i


            
 
 

You can get advantage of foreach loops when performing with collections. The subsequent code snippet illustrates how you can display screen all keys pertaining to the Ask for.Headers collection.




    @foreach (var k in this.Context.Ask for.Headers)
       
           
  • @k.Crucial

  •    


If you want to use a product in the view, you need to produce a product course as demonstrated in the code snippet specified beneath.

community course Author
   
        community int Id get established
        community string FirstName get established
        community string LastName get established
   

To make things easy, produce the product course in the Designs alternative folder. You can use this product in the view as illustrated in the code snippet specified right here:

    @product Author 
   
     
           
  • Author Id: @Product.Id
  •  
           
  • Very first Identify: @Product.FirstName
  •  
           
  • LastName: @Product.LastName
  •  
       

The Razor View Engine is extra innovative than its before counterpart, providing a friendlier syntax for building HTML code from templates. Observe that Razor is a basic reason templating engine — you can use it any where to render HTML.

You can also do the job with 3rd social gathering view engines, these types of as Spark, SharpDOM, and NDjango, in ASP.Web Main MVC. I’ll reveal how to produce a tailor made view engine in ASP.Web Main MVC in a afterwards publish right here.

Copyright © 2021 IDG Communications, Inc.