A new feature has introduced with Asp.Net Core 2.0 and it is a Razor Page. So, we can say, now we have a new type of template that is very much similar to MVC that is Razor Page.

 

Why Razor Page.

When you create an MVC project which has controller, view, model, view-model, routing etc which group together to run your application and if you are adding or modifying one single functionality than you have to change everywhere in MVC.

But Razor Page is only for small application where you have limited functionality which all depends on your Razor Page. If you would like to make any changes then you have to manipulate you Razor Page [.cshtml]. From separating the logic from razor page, you can create code-behind file which has .cshtml.cs extension.

 

Create Razor Page Application

To create Razor Page application, you should have Visual Studio 2017 with version 15.3 or above with .Net Core SDK 2.0 installed on your system. You can download .Net Core SDK 2.0 from Here and update your Visual Studio using “Visual Studio Installer”.

For creating new Razor Page application, go to File menu and choose New and then select Project, as usual, we do for creating a new project.

From the new project window, choose .Net Core from the left panel and “Asp.Net Core Web Application” from the center panel and provide the name of the application and location to save it and click to OK.

Asp.Net Core Razor Page

 

From the next window, you have to choose the template which is responsible to create Razor page and that is “Web Application” as shown in below image. Change the authentication to “No Authentication” and click to OK.

Razor Page Template

 

After clicking OK, it will take few seconds to configure your Razor Page Application. And finally, it will create your app as follows.

Razor Page Structure

Above is the basic structure of the Razor Page. It is much like MVC application but here you can see there are not Controller and Model folder. It is an important folder “Pages” which contains all the razor pages and a corresponding code-behind file.  Code behind files or Model Pages are basically use for separation of concern. Other things, like Program.cs and Startup.cs, are most likely similar to MVC.

 Now you can run the application and see the output as below screenshot shown.

Razor Page in Asp.Net Core

To add new razor page, just right click Pages folder or any folder inside Pages and choose Add > Razor Page to add razor page directly.

Add New Razor Page

It will open a new window, from where you can choose your razor page actual type. You might be using Razor with Entity Framework or you would like to write CRUD code automatically using Scaffold feature.

More about Razor Pages

Templating: The common razor template is same as MVC like “_viewStart.cshtml”, “_layout.cshtml”, “about.cshtml” etc, but only folder structure has changed here with Razor Pages. In MVC, these have there predefined folder like for common template, we use “Shared” folder inside the View folder and for every functionality has there own View folder like Home, Employee etc.

@Page: Every razor page has a @Page directive which indicates that this is not normal MVC razor view, it is a Razor Page.

@page

@model AboutModel
@{
    ViewData["Title"] = "About";
}

<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>

<p>Use this area to provide additional information.</p>

 

Code Behind or Model Page:  To write server-side logic, we can create a code-behind cshtml.cs file as following code shown which contains all the server side login like get the data from the server, post the data on the server. Here we use OnGet and OnPost handler to get and post the data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesExample.Pages
{
    public class AboutModel : PageModel
    {
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Your application description page.";
        }
    }
}

We can also write Razor Page without code behind page using inline coding with @function directive.

 

Model Binding:

We can bind the property directly with Razor Page using the [BindProperty] attribute. Property decorated with [BindProperty] attribute will automatically be available on Razor page.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesExample.Pages.Employee
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public Employee employee { get; set; }

        public void OnGet()
        {
        }

        public void OnPost()
        {
            var data = employee;
        }
    }

    public class Employee
    {
        public int ID { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "Name lenght should be 1 to 50.")]
        [Display(Name = "Employee Name")]
        public string Name { get; set; }


        [Required]
        [StringLength(255, ErrorMessage = "Address lenght should be 1 to 255.")]
        [Display(Name = "Address")]
        public string Address { get; set; }
    }
}

On Razor page, just use the name of the property and bind the input control with this.

@page

@model RazorPagesExample.Pages.Employee.IndexModel
@{
    ViewData["Title"] = "Employee Page";
}

<h2>@ViewData["Title"]</h2>
<div class="row">
    <div class="col-md-6">
        <form method="post">
            <div class="form-group">
                <label asp-for="employee.Name"></label>
                <input asp-for="employee.Name" class="form-control" />
                <span asp-validation-for="employee.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="employee.Address"></label>
                <input asp-for="employee.Address" class="form-control" />
                <span asp-validation-for="employee.Address" class="text-danger"></span>
            </div>

            <button type="submit" class="btn btn-default">Add Employee</button>
        </form>
    </div>
</div>

 

Model Auto-Updating: the Defined model with Razor page will update automatically on Code-Behind file. You don’t take care to bind your model with a specific operation. Any changes in the model data will get reflected in Model itself.

You can see with above code if you click on “Add Employee” button and passing correct data to avoid the error than data will bind with model and reflect on OnPost handler as follows. Here we are not passing model as the parameter as we do in MVC.

Razor Page Model Binding

Tag Helpers: As we all know tag helper is basically a feature of Asp.Net MVC and has included with Razor Page. Now you can bind your data with Razor Page directly using Tag Helpers. As following code shows that we are using so many Tag Helpers here like “asp-for”, “asp-validation-for” etc;

<form method="post">
            <div class="form-group">
                <label asp-for="employee.Name"></label>
                <input asp-for="employee.Name" class="form-control" />
                <span asp-validation-for="employee.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="employee.Address"></label>
                <input asp-for="employee.Address" class="form-control" />
                <span asp-validation-for="employee.Address" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-default">Add Employee</button>
</form>

 

Handlers: we use handlers to perform a server-side operation like getting the data, posting the data. These handlers are something like Http Verb we used in MVC like Get(), Post() etc.

As a prefix, we use “On” with Http Verb in Razor Page which indicate as an event or handlers as OnGet() or OnGetAsync(), OnPost() or OnPostAsync() etc.

 

Routing: As compare to MVC routing, Razor Page routing is very simple. We don’t have to write code manually for simple routing. All the pages inside Pages folder will call by file name after the domain name.

http://localhost:51068/index

http://localhost:51068/about

http://localhost:51068/employee/index

If you would like to pass the parameter with URL than you can add it with @page directive as following; Here you can see I am passing one id which is an integer type.

@page "{id:int}"

@model RazorPagesExample.Pages.Employee.IndexModel
@{
    ViewData["Title"] = "Employee Page";
}

 

So, when you call the URL, you have to pass the ID which should be integer type as below URL.

http://localhost:51068/employee/index/1

Razor Page Location

Routing URL

/Pages/Index.cshtml

OR /index

/Pages/About.cshtml

/about

/Pages/Employee/Index.cshtml

/employee OR /employee/index

/Pages/Employee/Index.cshtml with ID parameter

 /employee/index/1

 

Security: When talking about security with Razor Page like CSRF attack than we don’t need to manual code to protect our application from outer world as we do in MVC. We don’t need to add AntiRequestForgery Token or no need to verify it. These tasks are done by Razor Page automatically internally.

 

Conclusion

So, today we have learned about Asp.Net Core 2.0 Razor Page with its fundamentals.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks