Razor pages support has been added to asp.net core MVC which makes coding page-focused scenarios easier and more productive. Razor page support is enabled in Startup.cs file as
public class Startup { public void ConfigureServices(IServiceCollection services) { // Includes this line to support for Razor Pages and controllers. services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(); } }
You must define Razor pages inside Pages folder to be able to make routing work correctly.
Razor pages skips the dependency of being routed via controllers and make use of existing features like Tag helpers, Html helpers as well as model bindings. A typical Razor Page will look like below:
@page @model HelloWorldModel @using Microsoft.AspNetCore.Mvc.RazorPages @functions { public class HelloWorldModel : PageModel { public string Hello { get; private set; } = "Hello World: "; public void OnGet() { Hello += $" Welcome to Asp.net Coe 2.0"; } } } <h2>Hello World</h2> <p> @Model.Hello</p>
@page directive must be the first razor directive on your page and it lets you skip the routing via controller, rather the page directive makes the entire file behave like an MVC action and thus it can receive request directly from IIS.
Razor can work as inline model as shown in above example in which case the code must be written in @function block or we can make Razor work in code behind syntax as well like in below example:
Here is how HelloWorld.cshtml will look like
@page @model HelloWorldModel @using Microsoft.AspNetCore.Mvc.RazorPages <h2>Hello World</h2> <p> @Model.Hello</p>
And here goes HelloWorld.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages; using System; namespace HelloWorldCore2 { public class HelloWorldModel : PageModel { public string Hello { get; private set; } = "Hello World: "; public void OnGet() { Hello += $" Welcome to Asp.net Coe 2.0"; } } }