Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between Razor pages and MVC in ASP.NET Core

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "what is the difference between Razor page and MVC in ASP.NET Core". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope that this article "what is the difference between Razor page and MVC in ASP.NET Core" can help you solve the problem.

Basics: what is an ASP.NET Razor page?

Razor pages are very similar to the view components used by ASP.NET MVC developers in that they all share the same syntax and functionality.

The most critical difference is that the model and controller code are also included in the Razor page. It is more like a MVVM (Model-View-ViewModel) framework that supports two-way data binding, a simpler development experience, and independent concerns.

The following is the most basic example of a Razor page, with code embedded in the @ functions block, but it is recommended that you put the PageModel code in a separate file. This is more like the way we write code in an ASP.NET WebForms file.

@ page@model IndexModel@using Microsoft.AspNetCore.Mvc.RazorPages@functions {public class IndexModel: PageModel {public string Message {get; private set;} = "In page model:"; public void OnGet () {Message + = $"Server seconds {DateTime.Now.Second.ToString ()}";}} In page sample

@ Model.Message

We now have two choices: ASP.NET MVVM or MVC

We now have two choices, one for MVC and the other for MVVM framework. I'm not going to introduce all the details of MVC vs MVVM. This is illustrated in detail with some examples in this article. The MVVM framework is most concerned with the bidirectional binding of the data model.

MVC is suitable for applications with a large number of dynamic server views, single-page applications, REST API, and AJAX calls. Razor pages are ideal for simple pages that are read-only or perform basic data entry.

MVC is very popular in Web applications in most programming languages recently, but it also has its advantages and disadvantages. ASP.NET WebForms is designed as a MVVM solution, and you can think of Razor pages as an evolution of WebForms.

Advantages and disadvantages of Razor pages

Based on the fact that I am using the new Razor pages, here is a summary of the pros and cons and how I feel about using them.

Pros: more organized

I don't know about you, but the first time I used ASP.NET MVC, I spent a lot of time trying to figure out how it works. Naming rules and dynamically creating routes lead to a lot of rules that I'm not used to. In fact, from the path "/ Home/" to HomeController.Index (), it loads a view file from "Views\ Home\ Index.cshtml", which feels amazing at first.

The Razor page is more organized. You have a Razor view and background code file, just like WebForms, unlike controllers, views, and models corresponding to MVC that are stored in separate directories with separate files.

Compare the MVC project with the Razor page project (more code differences will be covered later in this article).

Comparison of MVC and Razor page files

Pros: single responsibility

If you have used the MVC framework before, you may see some huge controller classes that contain many different Action. They are like a virus that increases over time.

With Razor pages, each page is independent, and the view and code are organized together, following the principle of single responsibility.

Using Handlers to realize multiple GET and POST Action

By default, Razor pages are designed to have a single OnGetAsync and OnPostAsync Action methods; if you want to have different Action in a single page, you need to use a so-called Handler. If your page has AJAX callbacks, multiple form submissions, or other scenarios, you need to use it.

For example, if you use Kendo Grid and want to load Grid data through an AJAX call, you need to use Handler to handle the AJAX call. Any type of single-page application will use a lot of Handler, or you will point all these AJAX calls to the MVC controller.

I added a method called OnGetHelloWorldAsync () to the page. How do we call it?

From my research, there are three different ways to call Handler:

Querystring-example: "/ managepage/2177/?handler=helloworld"

Define the route in the view: @ page "{handler?}", and then include "/ helloworld" in the Url

Define the submit button in the view-example:

Learn more about how to have multiple Handlers on a single page here.

Why you should use the Razor page!

Razor pages are the perfect solution for web applications, and I may raise a dispute. It is clear at a glance that any HTML "page" in your application is a real page. Currently, MVC Action can return HTML views, JSON, files, or anything. Use Razor pages to force separation between page loading and AJAX callback services.

Come to think of it, this forced separation solves a lot of problems.

Razor PageMVCHTML ViewsREST API calls, SOA

This will prevent the MVC controller from mixing different "pages" with Action in a large number of Action,MVC applications, as well as AJAX callbacks and other features.

Of course, I haven't actually used this approach of development, which could be a failure or a success, and only time can tell the community how to use Razor pages.

Code comparison between ASP.NET Razor page and MVC

As part of the Razor page, I built a very simple Form form in the MVC and Razor pages. Let's take a look at the code between. It has only a text box and a submit button.

This is the MVC view:

@ model RazorPageTest.Models.PageClass Client

This is the MVC controller (the data model is PageClass, with only two properties, very simple).

Public class HomeController: Controller {public IConfiguration Configuration; public HomeController (IConfiguration config) {Configuration = config;} public async Task ManagePage (int id) {PageClass page; using (var conn = new SqlConnection (Configuration.GetConnectionString ("contentdb") {await conn.OpenAsync () Var pages = await conn.QueryAsync ("select * FROM PageData Where PageDataID = @ p1", new {p1 = id}); page = pages.FirstOrDefault ();} return View (page) } [HttpPost] [ValidateAntiForgeryToken] public async Task ManagePage (int id PageClass page) {if (ModelState.IsValid) {try {/ / Save to the database using (var conn = new SqlConnection (Configuration.GetConnectionString ("contentdb") {await conn.OpenAsync () Await conn.ExecuteAsync ("UPDATE PageData SET Title = @ Title WHERE PageDataID = @ PageDataID", new {page.PageDataID, page.Title});} catch (Exception) {/ / log it} return RedirectToAction ("Index", "Home") } return View (page);}}

Now let's compare the Razor page.

Razor page:

@ page "{id:int}" @ model RazorPageTest2.Pages.ManagePageModel ManagePage

This is Razor PageModel, also known as background code:

Public class ManagePageModel: PageModel {public IConfiguration Configuration; public ManagePageModel (IConfiguration config) {Configuration = config;} [BindProperty] public int PageDataID {get; set;} [BindProperty] public string Title {get; set } public async Task OnGetAsync (int id) {using (var conn = new SqlConnection (Configuration.GetConnectionString ("contentdb")) {await conn.OpenAsync (); var pages = await conn.QueryAsync ("select * FROM PageData Where PageDataID = @ p1", new {p1 = id}); var page = pages.FirstOrDefault () This.Title = page.Title; this.PageDataID = page.PageDataID;} return Page () } public async Task OnPostAsync (int id) {if (ModelState.IsValid) {try {/ / Save to the database using (var conn = new SqlConnection (Configuration.GetConnectionString ("contentdb") {await conn.OpenAsync () Await conn.ExecuteAsync ("UPDATE PageData SET Title = @ Title WHERE PageDataID = @ PageDataID", new {PageDataID, Title});} catch (Exception) {/ / log it} return RedirectToPage ("/") } return Page ();}} differential decryption

The code between the two is almost the same, and here are the main differences:

The code of the MVC view is exactly the same, except for @ page at the top of the Razor page

ManagePageModel has OnGetAsync and OnPostAsync methods, replacing the two "ManagePage" Action in the MVC controller

ManagePageModel contains two attributes that were previously separate in PageClass.

HTTP POST requests in MVC, passing objects to MVC's Action (for example, ManagePage (int id,PageClass page)); using Razor pages, you can use two-way data binding. In order for the Razor page to use two-way data binding correctly, my two attributes (PageDataID, Title) use the [BindProperty] tag.

This is the end of the content about "what is the difference between Razor pages and MVC in ASP.NET Core". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report