aspdotnet_razor_page.md - brainchildservices/curriculum GitHub Wiki
Slide 1
What is razor page and how it works with get and post
Razor Pages
is a newer, simplified web application programming model. Each Razor Pages file found under the Pages directory equates to an endpoint. In a Razor Page we can use HTML and with the help of @
Symbol we can use C# as well. Example:-
Above images shows the basic View of a Razor Page
Slide 2
To create a Razor Page in VS Code
- You can Copy Paste and Rename an existing Razor Pages
- Right Click on the Pages Folder and add New file, make sure the file extension is .cshtml
A Razor Page Contains a Code behind file, if you create a Razor Page Named Test.cshtml
it should contain a file named Test.cshtml.cs
Once you created both the files it should look like
Razor Page:-
Slide 3
Code Behind:-
in code behind page we must include the Page Model Property otherwise you’ll not be able to create a connection between code behind and Razor Page.
Slide 4
By convention, the PageModel class file has the same name as the Razor Page file with .cs appended. For example, the previous Razor Page is Pages/Index2.cshtml. The file containing the PageModel class is named Pages/Index2.cshtml.cs.
Slide 5
Handler methods in Razor Pages are also based on naming conventions. The basic methods work by matching HTTP verbs used for the request to the name of the method, and they are prefixed with "On": OnGet()
, OnPost()
, OnPut()
etc. They also have asynchronous equivalents: OnPostAsync()
, OnGetAsync()
etc. The following example illustrates basic usage in a single Razor pages file:Handler method for
Slide 6
Sample WebApp:-
Code behind – Area.cshtml.cs
Slide 7
Razor Page– Area.cshtml
Slide 8
OnGet
is called on a Razor Page to initialize the state for the page.
When the page is first navigated to, the required page as per the URL given by the user, content is displayed because the HTTP GET verb was used for the request, firing the OnGet()
handler.
So in our case when we navigate to https://localhost:5001/Area
We can see a page like this,
You can see in the Developer toolbar, network tab the get method initiated
Slide 9
OnPost()
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
The Handler method for POST operation accepts the values sent from the Razor Page through Model class object received as parameter.
SLide 10
In the above image you can see the Post method is accessed,
As you can see, the form is submitted and the values sent from Razor page through Model class object received as parameter.