Register Form In ASP.NET MVC Core 3.0

Today in this article I will explain how to create a registration form in ASP.NET MVC core. We will look at it step by step. To understand this article I recommend you read my previous articles, linked below. This article is a continuation of previous articles.

Here is the complete code,

Step 1. Start up Visual Studio 2019. Now click on Create New Project Choose ASP.NET Core Web Application and click on “Next".

Next

After clicking next, another wizard will open. Under the project name, give a meaningful name to your project, and click on Create.

Configure

That will open up another new wizard select ASP.Net Core 3.0 from the dropdown. If not, select default. Choose the Web Application (Model-View-Controller) template and click on create which will create your first ASP.Net Core Application.

ASP.NET

Step 2. Click on tools, select Nuget Package Manager, then click on manage Nuget Package for solution. Now click on the browse tab then search for the following packages and install them.

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Relational
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore

Step 3. Now create a folder called ViewModel and “Add” a class with the name RegisterViewModel. We will use this as a model for registering.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace RegistrationFormCore.ViewModels
{
    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Your password and confirm password do not match")]
        public string ConfirmPassword { get; set; }
    }
}

Step 4. Now under the project, create a folder with the name Controllers. After creating the “Controllers” folder, right-click on the “Controllers” folder and add a controller.

Controllers

A window will appear. Choose MVC Controller-Empty and click "Add".

MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to AccountController and click on "Add". The AccountController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Account.

Add

Step 5. Now “Add” IActionResultmethod with the name Register. Write the following below code to register the user.

Controller class code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using RegistrationFormCore.ViewModels;

namespace RegistrationFormCore.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new IdentityUser
                {
                    UserName = model.Email,
                    Email = model.Email
                };
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return View();
        }
    }
}

Step 6. Now right-click on the register action method and “Add View” with the default name Register to click on “Add”. It will be added under the views folder; account folder with Register.cshtml.

@model RegistrationFormCore.ViewModels.RegisterViewModel   

@{   
    ViewData["Title"] = "Register";   
}   

<p class="row">   
    <p class="col-md-6 mx-auto">   
        <p class="card">   
            <p class="card-header bg-danger text-white">   
                <h5 class="text-uppercase text-center">Registration Form</h5>   
            </p>   
            <p class="card-body">   
                <form asp-action="Register">   
                    <p asp-validation-summary="All" class="text-danger"></p>   
                    <p class="form-group">   
                        <label asp-for="Email"></label>   
                        <input asp-for="Email" class="form-control"/>   
                        <span asp-validation-for="Email" class="text-danger"></span>   
                    </p>   
                    <p class="form-group">   
                        <label asp-for="Password"></label>   
                        <input asp-for="Password" class="form-control"/>   
                        <span asp-validation-for="Password" class="text-danger"></span>   
                    </p>   
                    <p class="form-group">   
                        <label asp-for="ConfirmPassword"></label>   
                        <input asp-for="ConfirmPassword" class="form-control"/>   
                        <span asp-validation-for="ConfirmPassword" class="text-danger"></span>   
                    </p>   
                    <input type="submit" value="Register" class="btn btn-sm btn-success text-uppercase rounded-0"/>   
                </form>   
            </p>   
        </p>   
    </p>   
</p>   

Step 7. Now modify _Layout. cshtm and “Add” a link with Register.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RegistrationFormCore</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <p class="container">
                <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">RegistrationFormCore</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <p class="navbar-collapse collapse">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                        </li>
                    </ul>
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <a class="nav-link" asp-controller="Account" asp-action="Register">Register</a>
                        </li>
                    </ul>
                </p>
            </p>
        </nav>
    </header>
    <p class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </p>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @RenderSection("Scripts", required: false)
</body>
</html>

Step 8. Now press ctrl+F5 and run your project.

Register