Razor page is a new application template introduced with asp.net core framework, though we are familiar with razor page in mvc, but this razor page lifecycle works little differently, let’s learn!
Razor Page (chtml.cs) in Asp.Net Core is just like Aspx.cs in earlier version of Asp.net, Razor Page is built on top of ASP.NET Core MVC, but you don’t need any previous MVC knowledge, razor pages are very light weight and easy to work with.
using Microsoft.AspNetCore.Mvc.RazorPages; namespace RazorPages.Pages { public class IndexModel : PageModel { [BindProperty] public string Email { get; set; } } }
To work with razor page application, we need to add the reference of Microsoft.AspNetCore.Mvc.RazorPages;
assembly.
Creating constructor in razor page for DI implementation.
public class IndexModel : PageModel { IWebHostEnvironment _webHost; IConfiguration _configuration; public IndexModel(IWebHostEnvironment webHost, IConfiguration configuration) { _webHost= webHost; _configuration = configuration; } }
Right click on Page folder => Add => Razor Page=>
There you probably see three options Razor Page, Razor Page using Entity Framework and Razor Page using Entity Framework (CRUD)
(_)
@page
Here are few characteristic of Razor Pages in Asp.Net Core.
Add Property in Model
Notice every property in model has to have a BindProperty attribute.
, then only you can access this property while form in submitted, BindProperty is new in Asp.net Core, was not there in earlier version.
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace RazorPages.Pages { public class IndexModel : PageModel { [BindProperty] public string Email { get; set; } } }
@page @model IndexModel @{ ViewData["Title"]="Page Title Here" }
When you create razor page with model, a code behind file is created
Example.cshtml.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace LearnRazorPages.Pages { public class IndexModel : PageModel { public void OnGet() { } } }
Example.cshtml: here is a simple form with three fields, the way we used to write in classic asp, php etc
<form method="post"> <div>Name: <input name="name"/> </div> <div>Name: <input name="email"/> </div> <div>Name: <input name="mobile"/> </div> <div> <input type="submit"/> </div> </form>
Once you submit the form, you can access the submitted values in your codebehind OnPost() method
Example.cshtml.cs:public void OnPost() { var name = Request.Form["name"]; var email = Request.Form["email"]; var mobile = Request.Form["mobile"]; // now you have all submitted values in local variables }
You should also read following post to learn more about PageModel, Handler Methods, leveraging Model Binding, Handler method parameters etc.