Creating User Registration Form In ASP.NET Core MVC Web Application

Introduction

 
In this article I will explain how to create a user registration form in ASP.NET Core MVC application. An MVC application consists of model, view and controller. In this application I will create and scaffold a model to work with database and store user details in SQL Server database. The controller will be responsible for selecting a view to be displayed to the user and provides the necessary data model to store data on to the SQL Server database. The controller manages how the application would respond to the post request made by the user.
 

Creating ASP.NET Core MVC web application

 
Before writing the coding part of ASP.NET Core MVC application, first we need to create a table in SQL Server database. The table can be created with the help of following SQL query.
  1. create table UserRegistration    
  2. (    
  3.  UserId int not null primary key identity(1,1),    
  4.  Username nvarchar(150),    
  5.  Pwd nvarchar(100),    
  6.  Confirmpwd nvarchar(100),    
  7.  Email nvarchar(150),    
  8.  Gender char,    
  9.  MaritalStatus nvarchar(100)    
  10. );     
Now we will create a new ASP.NET Core MVC application as follows.
 
Creating User Registration Form In ASP.NET Core MVC Web Application
 
Here we will select ASP.NET Core Web application, provide project name and select model-view-controller as web application template.
 
Now we will be adding a connection string inside appsettings.json to connect to the SQL Server database.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "Myconnection""Data Source=DESKTOP-QGAEHNO\\SQLEXPRESS;Initial Catalog=profiledb;Integrated Security=True"  
  4.   },  
  5.   "Logging": {  
  6.     "LogLevel": {  
  7.       "Default""Information",  
  8.       "Microsoft""Warning",  
  9.       "Microsoft.Hosting.Lifetime""Information"  
  10.     }  
  11.   },  
  12.   "AllowedHosts""*"  
  13. }  
The next step is to add a class named user inside models folder. Inside user class, we will be defining properties required to interact with the registration form.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace UserReg.Models  
  8. {  
  9.     public class User  
  10.     {  
  11.         [Key]  
  12.         public int UserId { getset; }  
  13.   
  14.         [Required(ErrorMessage ="Please Enter Username..")]  
  15.         [Display(Name = "UserName")]  
  16.         public string Username { getset; }  
  17.   
  18.         [Required(ErrorMessage ="Please Enter Password...")]  
  19.         [DataType(DataType.Password)]  
  20.         [Display(Name ="Password")]  
  21.         public string Pwd { getset; }  
  22.   
  23.         [Required(ErrorMessage = "Please Enter the Confirm Password...")]  
  24.         [DataType(DataType.Password)]  
  25.         [Display(Name = "Confirm Password")]  
  26.         [Compare("Pwd")]  
  27.         public string Confirmpwd { getset; }  
  28.   
  29.         [Required(ErrorMessage = "Please Enter Email...")]  
  30.         [Display(Name = "Email")]  
  31.         public string Email { getset; }  
  32.   
  33.         [Required(ErrorMessage = "Select the Gender...")]  
  34.         [Display(Name = "Gender")]  
  35.         public string Gender { getset; }  
  36.   
  37.         [Required(ErrorMessage = "Select the Marital Status...")]  
  38.         [Display(Name = "Marital Status")]  
  39.         public string MaritalStatus { getset; }  
  40.   
  41.   
  42.     }  
  43. }  
Here user id is a primary key and to each and every property the required validation has been assigned so that if a user tries to click the submit button without filling the registration form, the application will throw an error.
 
Now we will define another class named ApplicationUser to add a DbContext to connect and query the database.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.EntityFrameworkCore;  
  6.   
  7. namespace UserReg.Models  
  8. {  
  9.     public class ApplicationUser:DbContext  
  10.     {  
  11.         public ApplicationUser(DbContextOptions<ApplicationUser> options): base(options)  
  12.         {  
  13.   
  14.         }  
  15.         public DbSet<User> UserRegistration { getset; }  
  16.     }  
  17. }  
Here we are adding the DbSet property to query the database.
 
Now within startup.cs class, we need to add services for application user class and connection string inside configureServices method.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddDbContext<ApplicationUser>(options => options.UseSqlServer(Configuration.GetConnectionString("Myconnection")));  
  4.             services.AddControllersWithViews();  
  5.         }  
Now we will be adding a controller named registration to define action methods required to make a post request to the server and submit user details to the server.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.EntityFrameworkCore;  
  7. using UserReg.Models;  
  8.   
  9. namespace UserReg.Controllers  
  10. {  
  11.     public class RegistrationController : Controller  
  12.     {  
  13.         private readonly ApplicationUser _auc;  
  14.   
  15.         public RegistrationController(ApplicationUser auc)  
  16.         {  
  17.             _auc = auc;  
  18.         }  
  19.         public IActionResult Index()  
  20.         {  
  21.             return View();  
  22.         }  
  23.         public IActionResult Create()  
  24.         {  
  25.             return View();  
  26.         }  
  27.   
  28.         [HttpPost]  
  29.         [ValidateAntiForgeryToken]  
  30.         public IActionResult Create(User uc)  
  31.         {  
  32.             _auc.Add(uc);  
  33.             _auc.SaveChanges();  
  34.             ViewBag.message = "The user " + uc.Username + " is saved successfully";  
  35.             return View();  
  36.         }  
  37.     }  
  38. }  
The above code is to save user details to the table in ASP.NET Core MVC application.
 
The next step is to add a view page for the create action method defined inside the controller class. To add a view page, select the respective action method, right click and click on add view option at the top.
  1. @model UserReg.Models.User  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Create";  
  5. }  
  6.   
  7. <h1>User Registration Form in asp.net core mvc application</h1>  
  8. <hr />  
  9.   
  10. <div class="row">  
  11.     <div class="col-md-9">  
  12.         <form asp-action="Create">  
  13.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  14.               
  15.             <div class="form-group">  
  16.                 <label asp-for="Username" class="control-label"></label>  
  17.                 <input asp-for="Username" class="form-control" />  
  18.                 <span asp-validation-for="Username" class="text-danger"></span>  
  19.             </div>  
  20.             <div class="form-group">  
  21.                 <label asp-for="Pwd" class="control-label"></label>  
  22.                 <input asp-for="Pwd" class="form-control" type="password"/>  
  23.                 <span asp-validation-for="Pwd" class="text-danger"></span>  
  24.             </div>  
  25.             <div class="form-group">  
  26.                 <label asp-for="Confirmpwd" class="control-label"></label>  
  27.                 <input asp-for="Confirmpwd" class="form-control" type="password" />  
  28.                 <span asp-validation-for="Confirmpwd" class="text-danger"></span>  
  29.             </div>  
  30.             <div class="form-group">  
  31.                 <label asp-for="Email" class="control-label"></label>  
  32.                 <input asp-for="Email" class="form-control" />  
  33.                 <span asp-validation-for="Email" class="text-danger"></span>  
  34.             </div>  
  35.             <div class="form-group">  
  36.                 <label asp-for="Gender" class="control-label"></label>  
  37.                 @*<input asp-for="Gender" class="form-control" />*@  
  38.   
  39.                 <input type="radio" name="Gender" value="M" />Male  
  40.                 <input type="radio" name="Gender" value="F" />Female  
  41.   
  42.                 <span asp-validation-for="Gender" class="text-danger"></span>  
  43.             </div>  
  44.             <div class="form-group">  
  45.                  <label asp-for="MaritalStatus" class="control-label"></label>  
  46.                    
  47.   
  48.                  <select asp-for="MaritalStatus">  
  49.                      <option selected disabled>Select Marital Status</option>  
  50.                      <option>Married</option>  
  51.                      <option>Unmarried</option>  
  52.                  </select>  
  53.                   
  54.                  <span asp-validation-for="MaritalStatus" class="text-danger"></span>  
  55.             </div>  
  56.                       
  57.             <div class="form-group">  
  58.                         <input type="submit" value="Save User Details" class="btn btn-primary" />  
  59.             </div>  
  60.             <b>@ViewBag.message</b>  
  61.                 </form>  
  62.             </div>  
  63.         </div>  
  64.   
  65.         <div>  
  66.             <a asp-action="Index">Back to List</a>  
  67.         </div>  
  68.   
  69.         @section Scripts {  
  70.             @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  71.         }  
Inside create.cshtml view page, we have defined input fields for username, password, confirm password and email id. For gender and marital status, radio buttons and dropdown list has been designed. At the bottom, save button has been designed to submit user details to the database.
 

Output

 
The output of the web application is as follows:
 
Creating User Registration Form In ASP.NET Core MVC Web Application
 
If we try to save details without filling the input fields, the application will throw error messages as follows.
 
Creating User Registration Form In ASP.NET Core MVC Web Application
 
The database table after submitting user details will consist of the following records.
 
Creating User Registration Form In ASP.NET Core MVC Web Application
 

Summary

 
In this article, I explained how to create a registration form in an ASP.NET Core Web application. I created model classes to define properties for the registration form and dbset properties to connect to the database. A controller has been created which selects a view to be displayed to the user and provides necessary data model to store data on to the SQL Server database. A view page has been created for a specific action method in which all the relevant input fields, radio buttons and dropdown lists have been designed. Proper code snippets along with output have been provided for each and every part of the application.