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.
- create table UserRegistration
- (
- UserId int not null primary key identity(1,1),
- Username nvarchar(150),
- Pwd nvarchar(100),
- Confirmpwd nvarchar(100),
- Email nvarchar(150),
- Gender char,
- MaritalStatus nvarchar(100)
- );
Now we will create a new ASP.NET Core MVC application as follows.
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.
- {
- "ConnectionStrings": {
- "Myconnection": "Data Source=DESKTOP-QGAEHNO\\SQLEXPRESS;Initial Catalog=profiledb;Integrated Security=True"
- },
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*"
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using System.ComponentModel.DataAnnotations;
-
- namespace UserReg.Models
- {
- public class User
- {
- [Key]
- public int UserId { get; set; }
-
- [Required(ErrorMessage ="Please Enter Username..")]
- [Display(Name = "UserName")]
- public string Username { get; set; }
-
- [Required(ErrorMessage ="Please Enter Password...")]
- [DataType(DataType.Password)]
- [Display(Name ="Password")]
- public string Pwd { get; set; }
-
- [Required(ErrorMessage = "Please Enter the Confirm Password...")]
- [DataType(DataType.Password)]
- [Display(Name = "Confirm Password")]
- [Compare("Pwd")]
- public string Confirmpwd { get; set; }
-
- [Required(ErrorMessage = "Please Enter Email...")]
- [Display(Name = "Email")]
- public string Email { get; set; }
-
- [Required(ErrorMessage = "Select the Gender...")]
- [Display(Name = "Gender")]
- public string Gender { get; set; }
-
- [Required(ErrorMessage = "Select the Marital Status...")]
- [Display(Name = "Marital Status")]
- public string MaritalStatus { get; set; }
-
-
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.EntityFrameworkCore;
-
- namespace UserReg.Models
- {
- public class ApplicationUser:DbContext
- {
- public ApplicationUser(DbContextOptions<ApplicationUser> options): base(options)
- {
-
- }
- public DbSet<User> UserRegistration { get; set; }
- }
- }
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.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationUser>(options => options.UseSqlServer(Configuration.GetConnectionString("Myconnection")));
- services.AddControllersWithViews();
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using UserReg.Models;
-
- namespace UserReg.Controllers
- {
- public class RegistrationController : Controller
- {
- private readonly ApplicationUser _auc;
-
- public RegistrationController(ApplicationUser auc)
- {
- _auc = auc;
- }
- public IActionResult Index()
- {
- return View();
- }
- public IActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public IActionResult Create(User uc)
- {
- _auc.Add(uc);
- _auc.SaveChanges();
- ViewBag.message = "The user " + uc.Username + " is saved successfully";
- return View();
- }
- }
- }
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.
- @model UserReg.Models.User
-
- @{
- ViewData["Title"] = "Create";
- }
-
- <h1>User Registration Form in asp.net core mvc application</h1>
- <hr />
-
- <div class="row">
- <div class="col-md-9">
- <form asp-action="Create">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
-
- <div class="form-group">
- <label asp-for="Username" class="control-label"></label>
- <input asp-for="Username" class="form-control" />
- <span asp-validation-for="Username" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Pwd" class="control-label"></label>
- <input asp-for="Pwd" class="form-control" type="password"/>
- <span asp-validation-for="Pwd" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Confirmpwd" class="control-label"></label>
- <input asp-for="Confirmpwd" class="form-control" type="password" />
- <span asp-validation-for="Confirmpwd" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Email" class="control-label"></label>
- <input asp-for="Email" class="form-control" />
- <span asp-validation-for="Email" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Gender" class="control-label"></label>
- @*<input asp-for="Gender" class="form-control" />*@
-
- <input type="radio" name="Gender" value="M" />Male
- <input type="radio" name="Gender" value="F" />Female
-
- <span asp-validation-for="Gender" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="MaritalStatus" class="control-label"></label>
-
-
- <select asp-for="MaritalStatus">
- <option selected disabled>Select Marital Status</option>
- <option>Married</option>
- <option>Unmarried</option>
- </select>
-
- <span asp-validation-for="MaritalStatus" class="text-danger"></span>
- </div>
-
- <div class="form-group">
- <input type="submit" value="Save User Details" class="btn btn-primary" />
- </div>
- <b>@ViewBag.message</b>
- </form>
- </div>
- </div>
-
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
-
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }
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:
If we try to save details without filling the input fields, the application will throw error messages as follows.
The database table after submitting user details will consist of the following records.
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.