Razor page–asp.net Core 2.0 new features

Source: Internet
Author: User
Tags dotnet

Razor Page Introduction Preface

Last week, the long-awaited ASP. Net Core 2.0 was released in advance, and all of a sudden, 2.0 brought a lot of new features and new features, of which razor page attracted my attention, as a web programmer, Any web framework under ASP will pay special attention, because each time a new framework comes out, it means a revolution. Whether this razor page can bring a different experience, let's have a look.

What is Razor Page

As we all know, in ASP. Razor is one of its view engines. Today we introduce the Razor page is a web framework, it is a simplified MVC framework, if you have been a WebForm developer, you will find that Razor page is a bit like web Form, a page, a class.

We may have doubts, we are now ASP. NET MVC is very well, why do we need a new framework? In my opinion, MVC is really strong enough, but because it is too strong, it has become a disadvantage. When our business is getting bigger, do you feel that one of your controllers is in a messy mess? When we divide the business module more, do you have a headache for your model creation? When we create a new view, we need to add 1 view,1 model in the MVC layer, modify a controller, whenever this time, I will be wondering if this is not a violation of open-closed Principle (open to the extension, the change is closed)! This time I will think of the old WebForm, now no need, we have razor Page, a more lightweight MVC (I think more like MVVM).

How to create a razor Page

There are many ways to create a Razor page project, and the simplest is to take advantage of the dotnet command, and I recommend that you use Visual Studio 2017 (the strongest IDE in the universe). To create a razor Page, you need to install the. Net Core 2.0 SDK First, and if you want to use VS2017 to create it, you must also update to version 15.3 above

dotnet Command mode creation

Open cmd or PowerShell tool, first check if your dotnet version is 2.0.0

Dotnet–version

First through the command, to the directory where you need to create the project, I am here for the e-Disk Demos directory: CD E:\demos\RazorPageDemo1

Dotnet New Razor

Enter the above command, you have created the Razorpage project, here say Dotnet 2.0 default is automatic restore, you can also be closed through the--no-restore option. We can run directly through the command dotnet run and see the page similar to the previous MVC creation.

Enter Dir, and we'll look at what's generated:

Unlike previous MVC, we no longer see the Model,view,controller directory, instead of the pages directory, which is the main working directory of our Razor page.

Visual Studio 2017 creates razor Page

Creating with Visual Studio 2017 is very handy (the strongest IDE in the universe), but we have to upgrade to 15.3 first, select New Project->.net core–> ASP. NET Core Web application after upgrade, then a dialog box pops up, Let's choose the template type:

A lot of templates, so excited Ah! We can't find the razor page here because the Razor page has become the default Web Application template, and the traditional MVC approach has become a "Web application (Model View controller)." Select "Web Application Template", click OK we will finish creating, through solution Explore, we can see:

Consistent with the way the command was created.

QuickStart Razor Pagehello Razor Page

We created the Razor page project from the previous section and ran directly through dotnet Run or F5 in vs. As we said above, in the Razor page project, our focus is in the pages directory, in VS Explore, We see a triangular arrow on the left side of the index.cshtml, and click to see the Index.cshtml.cs file, is not feeling back to the WebForm. Let's look at the code:

 Public class indexmodel:pagemodel{    publicvoid  onget ()    {    }}

Because our index page is not bound to any data, so here basically only inherit the Pagemodel,onget method is a convention, look at the MVC source code you will find it will get On{handler}{async} (). For example Onget, it will be executed at the time of Get index, we can make data binding through this Convention, it is known that under Razor page HttpMethod is also a handler, so the Razor page is handled by handler.

For example, we add a string-type property message in Indexmodel, which is assigned in Onget:

 Public void Onget () {    "This isa test! " ;}

Then we modify the following index.csthml:

@page @model indexmodel@{    viewdata["Title"] = "Home page";} <  class= "Row">   message: @Model. Message</  div>

Run, if we see Message:this is a test! on the page, the assignment succeeds.

is not very convenient, generally our web basically 80% in Get and post, special circumstances will appear other HttpMethod, of course our razorpage also support, but not recommended.

Now Pagemodel is a model,action,httpmethod, for the controller to use the file's own path + filename, such as the original HomeController, by default we can pass the '/' Access can also be accessed through '/home/', which is actually ambiguous, in order to avoid this situation, we have to modify the route, very inconvenient, and now, we just need to create the corresponding action in the pages home directory, Microsoft provides razor The corresponding URL relationship for the page,

Fast Custom Routing

Would you ask if you still support/controller/action/id?

Support, but you need to set up routing via @page on the cshtml page

@page "{Parameter:type}"

For example/address/province/city we only need to add the following on the address/index.cshtml page:

@page "{province}/{city}"

The question mark represents an optional parameter. The advantage is that we don't need to fill in the rules at the time of Registerroute, isn't it great!

It's like we were in a controller, get () and get (ID) represent get list and get single item, how to use it in Razor page?

Sorry, I did not find the best solution, originally I intend to @page "~/user/{id:int}", but the test results found not supported, because our page corresponds to a URL is also a directory, @page route when it does not recognize the absolute path and relative path, It will only add a map after the current path, that is, our URL becomes/users/user/{id}, the best solution is to create two directories, as follows:


Model binding

In razor page, data binding is very simple, as long as you add the [BindProperty] attribute on the property that needs to be bound.

 Public classindexmodel:pagemodel{ Public stringMessage {Get;Set; } [BindProperty] PublicUser TestUser {Get;Set; }} Public classuser{ PublicGuid UserID {Get;Set; }  Public  stringName {Get;Set; }}

The default model binding does not support the Get method, you need to use [BindProperty (supportsget=true)]

TempData Temporary data

TempData is a new feature of the ASP. NET Core 2.0, you only need to add the TempData feature to the properties in the Pagemodel. Plus the attributes of the TempData attribute, which can be passed through implicitly when you jump to a route or page.

What do you mean? For example, when you create a user, you will want to jump back to the user list page, and the user List page prompts to add the successful information, you can use the message property by adding the [TempData] feature, citing the example of Microsoft Docs:

 Public classcreatedotmodel:pagemodel{[TempData] Public stringMessage {Get;Set; } [BindProperty] PublicCustomer Customer {Get;Set; }  Public AsyncTask<iactionresult>Onpostasync () {if(!modelstate.isvalid) {returnPage (); }        //Todo Create a new customerMessage = $"Customer {customer.name} added"; returnRedirecttopage ("./index"); }}

After jumping to index, our Indexmodel message property (which needs to set the TempData attribute) will be assigned. A bit similar to the previous model pass, but not the same, feel the Bang Bang!

Some of the problems encountered

Q: The absolute path and relative path cannot be supported when customizing routing

A: It should be possible to achieve the goal by rewriting an interface, which I'll look at later

Q: Multiple handler are not supported in the same pagemodel, such as Onget, Ongetasync cannot be in the same Pagemodel

A: You can override the Ipagehandlermethodselector interface by yourself and then register to the service to be able to resolve it.

Q: When creating a new page with VS2017, a red line will appear on the page

A: Close the page and open ....

Written in the last

Recently work a bit busy, Core2.0 's appearance makes net circle boil, the appearance of Razorpage is let us this kind of web developer to be excited, today introduction of limited, after all is just come out of thing. Personally think Razor page is still very good, although there are some problems, if you encounter Razor page can not solve things, please combine MVC, foreign have great God is doing, but I believe that soon after, Razor page will be crazy appear in front of us, In particular, the micro-service architecture, simple and fast is the micro-service important.

Finally, recommend your own. Net Core Learning Group: 376248054

Razor page–asp.net Core 2.0 new features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.