Introduction
In this article, we will be working on the registration page of the ASP.NET Core razor page web application. We will be adding more properties to the default registration page. We will be adding properties such as Name, Address, City and Postal code, as the default registration page contains only a few properties such as email, ID, password and confirm password.
Creating ASP.NET Core Razor Pages Web Application
Inside Visual Studio, we will create an ASP.NET Core Razor Pages web application.
We have to change the Authentication to Individual Users Accounts. This will make sure that identity is scaffolded, to make use of login and registration functionality inside the project.
The project folder should look like the following:
Now we will work on register functionality, in register functionality, we only have email and password fields but we will add more fields such as Name, Address, City, Phone number and Postal code.
In order to add those properties inside the database, we have to extend the IdentityUser that has already been implemented and we have to add additional properties there.
So, we need to add a new model class to create new properties. To add a model class, right-click on the models folder, add a new class and name it ApplicationUser.
- using Microsoft.AspNetCore.Identity;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace SparkAutomation.Models
- {
- public class ApplicationUser : IdentityUser
- {
- public string Name { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string PostalCode { get; set; }
-
- }
- }
This ApplicationUser class is extending IdentityUser, that is it is an implementation of IdentityUser. Inside the ApplicationUser class, we are adding four properties such as Name, Address, City and Postal code.
Now we have to push these changes to the local database created earlier. So in order to push anything to the database, we need to make changes inside the ApplicationDbContext class created by default inside the Migration folder.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
- using Microsoft.EntityFrameworkCore;
- using SparkAutomation.Models;
-
- namespace SparkAutomation.Data
- {
- public class ApplicationDbContext : IdentityDbContext
- {
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
- : base(options)
- {
- }
- public DbSet<ApplicationUser> ApplicationUser { get; set; }
- }
- }
Inside ApplicationDbContext class, we have to create a new DbSet for ApplicationUser.
Now we will add a migration, so we will go to tools, then NuGet Package Manager and click on Package Manager Console.
To add a migration, type the following command inside the Package Manager Console.
- add-migration AddPropertiesToUser
If we go through the newly created migration file, we can see that it is adding columns such as Name, Address, City and Postal code to AspNetUsers table.
- using Microsoft.EntityFrameworkCore.Migrations;
-
- namespace SparkAutomation.Data.Migrations
- {
- public partial class AddPropertiesToUser : Migration
- {
- protected override void Up(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.AddColumn<string>(
- name: "Discriminator",
- table: "AspNetUsers",
- nullable: false,
- defaultValue: "");
-
- migrationBuilder.AddColumn<string>(
- name: "Address",
- table: "AspNetUsers",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "City",
- table: "AspNetUsers",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "Name",
- table: "AspNetUsers",
- nullable: true);
-
- migrationBuilder.AddColumn<string>(
- name: "PostalCode",
- table: "AspNetUsers",
- nullable: true);
- }
-
- protected override void Down(MigrationBuilder migrationBuilder)
- {
- migrationBuilder.DropColumn(
- name: "Discriminator",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "Address",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "City",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "Name",
- table: "AspNetUsers");
-
- migrationBuilder.DropColumn(
- name: "PostalCode",
- table: "AspNetUsers");
- }
- }
- }
Now we need to update the database to make changes inside of it. To update the database, type following command inside the Package Manager Console.
If we go back to the database, right-click on AspNetUsers table and click on view data. We can see all of the four new properties have been added inside the table.
After adding more properties inside the AspNetUsers table, we can add these properties inside the register page. In order to add more fields inside the registration page, we have to make changes inside the register razor page which has been auto-implemented by the identity.
We need to make changes inside register page model, because whenever we want to display anything the razor page, we need those properties inside page model.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- using System.Text.Encodings.Web;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.AspNetCore.Identity.UI.Services;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using Microsoft.AspNetCore.WebUtilities;
- using Microsoft.Extensions.Logging;
-
- namespace SparkAutomation.Areas.Identity.Pages.Account
- {
- [AllowAnonymous]
- public class RegisterModel : PageModel
- {
- private readonly SignInManager<IdentityUser> _signInManager;
- private readonly UserManager<IdentityUser> _userManager;
- private readonly ILogger<RegisterModel> _logger;
- private readonly IEmailSender _emailSender;
-
- public RegisterModel(
- UserManager<IdentityUser> userManager,
- SignInManager<IdentityUser> signInManager,
- ILogger<RegisterModel> logger,
- IEmailSender emailSender)
- {
- _userManager = userManager;
- _signInManager = signInManager;
- _logger = logger;
- _emailSender = emailSender;
- }
-
- [BindProperty]
- public InputModel Input { get; set; }
-
- public string ReturnUrl { get; set; }
-
- public IList<AuthenticationScheme> ExternalLogins { get; set; }
-
- public class InputModel
- {
- [Required]
- [EmailAddress]
- [Display(Name = "Email")]
- public string Email { get; set; }
-
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string Password { get; set; }
-
- [DataType(DataType.Password)]
- [Display(Name = "Confirm password")]
- [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
- public string ConfirmPassword { get; set; }
-
- [Required]
- public string Name { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string PostalCode { get; set; }
-
- [Required]
- public string PhoneNumber { get; set; }
- }
-
- public async Task OnGetAsync(string returnUrl = null)
- {
- ReturnUrl = returnUrl;
- ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
- }
-
- public async Task<IActionResult> OnPostAsync(string returnUrl = null)
- {
- returnUrl = returnUrl ?? Url.Content("~/");
- ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
- if (ModelState.IsValid)
- {
- var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
- var result = await _userManager.CreateAsync(user, Input.Password);
- if (result.Succeeded)
- {
- _logger.LogInformation("User created a new account with password.");
-
- var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
- code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
- var callbackUrl = Url.Page(
- "/Account/ConfirmEmail",
- pageHandler: null,
- values: new { area = "Identity", userId = user.Id, code = code },
- protocol: Request.Scheme);
-
- await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
- $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
-
- if (_userManager.Options.SignIn.RequireConfirmedAccount)
- {
- return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
- }
- else
- {
- await _signInManager.SignInAsync(user, isPersistent: false);
- return LocalRedirect(returnUrl);
- }
- }
- foreach (var error in result.Errors)
- {
- ModelState.AddModelError(string.Empty, error.Description);
- }
- }
-
-
- return Page();
- }
- }
- }
Inside InputModel class, we need to add all of the properties that we added inside ApplicationUser model class.
Now we need to make changes inside the register razor page to add fields related to those four properties.
After modifying the existing registration page and adding more fields to it, the final output should look like the below image:
Summary
In this article, I demonstrated how to create an ASP.NET Core Razor Pages web application. We completed the view for the register functionality, modified the existing registration page and added more properties inside the database to display newly created fields inside the register razor page.