Building A Simple Registration Form In ASP.NET MVC

Introduction

In this article, I will explain how to build a simple user registration form that will allow users to register using ASP.NET MVC.

MVC architecture in ASP.NET

MVC stands for Model, View, and Controller. MVC separates applications into three components - Model, View, and Controller.

  • Model: The model represents the shape of the data and business logic. It maintains the data of the application. Model objects retrieve and store model states in a database.
  • View: View is a user interface. The view displays data using the model to the user and also enables them to modify the data.
  • Controller: The controller handles the user request.

The flow of the user's request in ASP.NET MVC

ASP.Net MVC

  1. First user enters a URL in the browser
  2. It goes to the server and calls the appropriate controller.
  3. The Controller uses the appropriate View and Model creates the response and sends it back to the user.
  4. The controller handles the user's requests, so first we have to create a Controller.

Registration Form In ASP.NET MVC

For creating a registration form we have used one controller, two views, and one model class.

Step 1. First Create a Table in the Database (SQL Server 2012).

  1. Create a Database and name it as RegMVC.
  2. Add a table (here Table name: tblRegistration)
  3. Set primary key to Id column.
     Id column

Note. In this example, I set the ID to auto-increment so that the ID will be automatically generated for every newly added row. To do this select the Column name Id and in the column properties set the Identity Specification to yes.

Column name Id

Step 2. Create a new project in Visual Studio 2015.

  1. Open Visual Studio 2015-> click on file -> new-> project.
    New project
  2. Visual C#-> Web -> ASP.NET Web Application-> Write Project Name-> OK.
    Write Project Name
  3. Select the MVC template.
  4. Empty-> Click MVC Folder-> OK.
    MVC Folder
  5. MVC Folders are created.
    MVC Folders

Step 3. ADD ENTITY DATA MODEL.

  1. Right click Models Folder-> Add-> Class-> Visual C#-> Data-> ADO.NET Entity data Model-> Entry Name-> ADD
    Models Folder
    Class
  2. Entity Data Model Wizard dialog.
  3. Select EF Designer from Database-> Next->New Connection
    Model Wizard dialog
    Model
  4. Enter your server name-> Choose your authentication, I am using SQL Server authentication. So we need to provide the User Name and Password-> Select your database-> Test Connection-> ok.
    Choose your authentication
  5. Includes the sensitive data in the connection string->next->Choose version of Entity Framework.
    Choose version
  6. Include Database objects to your model-> Finish.
    Database objects
  7. Visual Studio will generate a database diagram for the table.
    Database diagram
  8. Now, you have an Entity Data Model file in your Model folder with all its necessary supportive files.
  9. The auto-generated entities file with DbContext inherited (registration.Context.cs).DbContext and DbSet that we need to establish a link between the model and the database."tblRegistration.cs" class, you will see all the properties. (Model Class).
  10. The model class is ready with all Properties(tblRegistration.cs file).
    Model class

Step 4.  CREATE A CONTROLLER.

  1. Go to the controller's folder-> Add-> Controller-> Select MVC 5 Controller Empty->Add.
    Select MVC 5 Controller
  2. It will open the Add Controller dialog as shown below.
    Add Controller
  3. Write Controller Name. Do not delete the word Controller. Remember, controller name must end with Controller.
    Write Controller
  4. This will create a HomeController class with the Index method in the HomeController.cs file under the Controllers folder, as shown below.
    HomeController

Step 5. Add View.

  1. Open a HomeController class -> right-click inside the Index method -> click Add View.
     Index method
  2. In the Add View dialogue box, keep the view name as Index. Choose Template Create (because we are inserting data in this Application). Select Model Class. Select Data Context Class. Click the Add Button.
    Add View dialogue box

Note. You will find this error. Just Rebuild the Project.

Rebuild the Project

After creating the view, it will look like below.

@model Registration.Models.tblRegistration
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>tblRegistration</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.FName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.LName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.LName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        }
    </div>
</body>
</html>

Step 6. Add a new action into your controller for the get method.

  1. Add the following Namespaces in the Controller.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Registration.Models;
    
  2. Write the following code in Controller Class. ( HomeController.CS Class).
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Registration.Models;
    
    namespace Registration.Controllers {
        public class HomeController : Controller {
    
            public ActionResult Index() {
                return View();
            }
    
            [HttpPost]
            public ActionResult Index(tblRegistration obj) {
                if (ModelState.IsValid) {
                    RegMVCEntities db = new RegMVCEntities();
                    db.tblRegistrations.Add(obj);
                    db.SaveChanges();
                }
                return View(obj);
            }
        }
    }
    

Code Explanation

  1. The Home Controller Class Contains two Action methods. The first Action method is [HttpGet], when you run the application this method will execute. The second Action method is [HttpPost], when the user clicks the Create button this Action method will execute.
  2. Model state.IsValid property validates each model property against the validation attributes used in the Model and it returns true or false.
  3. SaveChanges() method is called to save the data into the database.

Output

Output

In Database

Database


Similar Articles