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.
Let's understand the MVC architecture in ASP.NET
MVC stands for Model, View and Controller. MVC separates application into three components - Model, View and Controller.
- Model
Model represents the shape of the data and business logic. It maintains the data of the application. Model objects retrieve and store model state in a database.
- View
View is a user interface. View displays data using model to the user and also enables them to modify the data.
- Controller
Controller handles the user request.
The flow of the user's request in ASP.NET MVC.
- First user enters a URL in the browser
- It goes to the server and calls appropriate controller.
- The Controller uses the appropriate View and Model and creates the response and sends it back to the user.
- Controller handles user's requests, so first we have to create Controller
For creating a registration form we have used one controller, two views and one model class.
Step 1 First Create Table in Database (SQL Server 2012)
- Create Database and name it as RegMVC.
- Add table (here Table name: tblRegistration)
- Set primary key to Id column.
Note
In this Example I set the Id to auto increment so that the id will be automatically generated for every new added row. To do this select the Column name Id and in the column properties set the Identity Specification to yes.
Step 2 Create new project in Visual Studio 2015
- Open Visual studio 2015-> click on file -> new-> project.
- Visual C#-> Web -> ASP.NET Web Application-> Write Project Name-> OK.
- Select MVC template.
Empty-> Click MVC Folder-> OK.
- MVC Folders are created.
Step 3 ADD ENTITY DATA MODEL
- Right click Models Folder-> Add-> Class-> Visual C#-> Data-> ADO.NET Entity data Model-> Entry Name-> ADD
- Entity Data Model Wizard dialog.
Select EF Designer from Database-> Next->New Connection
- Enter your server name-> Choose your authentication, I am using SQL Server authentication. So we need to provide User Name and Password-> Select your database-> Test Connection-> ok.
- Includes the sensitive data in the connection string->next->Choose version of Entity Framework.
- Include Database objects to your model-> Finish.
- Visual Studio will generate a database diagram for the table.
Now, you have an Entity Data Model file in your Model folder with all its necessary supportive files.
The auto generated entities file with DbContext inherited (lRegistrationt.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).
- Model class is ready with all Properties(tblRegistration.cs file)
Step 4 CREATE A CONTROLLER
- Go to the controllers folder-> Add-> Controller-> Select MVC 5 Controller Empty->Add.
- It will open Add Controller dialog as shown below.
- Write Controller Name. Do not delete the word Controller. Remember, controller name must end with Controller.
- This will create HomeController class with Index method in HomeController.cs file under Controllers folder, as shown below.
Step 5 Add View
- Open a HomeController class -> right click inside Index method -> click Add View.
- 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 Add Button.
NOTE
You will find this error. Just 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 NEW ACTION INTO YOUR CONTROLLER FOR GET METHOD
- Add following Namespaces in Controller.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Registration.Models;
Write 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
- Home Controller Class Contain two Action methods. First Action method is [HttpGet], when you run the application this method will execute. Second Action method is [HttpPost], when user clicks Create button this Action method will execute.
- Modelstate.IsValid property validates each model property against the validation attributes used in the Model and it returns true or false.
- SaveChanges() method is called to save the data into the database.
Output
In Database