A Coder's Blog
Recently I installed Visual Studio 2017 and I wanted to try Razor Pages, a new feature of ASP.NET Core 2. According to Microsoft it makes coding page-focused scenarios easier and more productive.
For my test I decided to create a simple web page with a simple form where a user can subscribe to a website inserting name and email address. The same page will also show the list of users already registered.
With the introduction of Entity Framework Core 1.0 it is possible to use an in-memory data provider, this will spare us to use a local or external database.
For this test I downloaded and installed VS 2017 community edition. visual studio downloads
and I downloaded and installed from github .net core 2.0 .net core 2.0
In Visual Studio 2017 create a new .NET Core Project..
..select ASP.NET Core 2.0 and Web Application
Now the project has been created. Via Nuget packages I installed Microsoft.EntityFrameworkCore.InMemory
I created a new folder called DbModels, and I created the first class representing the user subscribing the service
I created my DbContext for Entity Framework, it implements DbContext class, and it contains the entity set “Subscribers”
The last step is to initialize the DbContext in the Startup.cs file, adding the following line inside the ConfigureServices method
Righ click on pages folder and add a new Razor Page. I called this page “Subscribe”
A SubscribeModel class is created automatically in the Subscrive.cshtml.cs file.
I’ve added a read-only field that represents my in-memory DB context and initialize it in the constructor.
I also added a property Subscriber with a BindProperty attribute for the model binding when I’m going to post using a form the subscriber details.
I also needed a List of all subscribers to show in the page
I created a method that handle the post of a new subscriber (The naming convention is OnPost[handler])
The last step is to write the client part in the Subscribe.cshtml
The form:
@Html.ValidationSummary() to show server side validation errors, asp-validation-summary=”All” for client side ones. On the submit input field I need to specify the name of the handler asp-page-handler=”add” (OnPost[handler])
I also wanted to display all the previous subscribers
The last step is to populate the Subscribers property in the OnGet method
To test it http://yourmachine/Subscribe