Here, I am going to demonstrate a simple login and registration form along with a simple admin panel in MVC, so that after registration users can easily log in and see their data in the admin panel.
I hope you are familiar with MVC Concepts but still, I write this blog in consideration for beginners so that they can easily understand. I am using MVC 4 in VS 2010. You can code in any VS.
Let us first start with the DATABASE SECTION.
STEP-1
First, create a table in SQL SERVER in your already created database or you can create a new one by using the below code,
- --Syntax:
- CREATE DATABASE database name;
-
- CREATE DATABASE Sample; //My DB name is Sample
Now, execute the below code to create a table in the database,
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[Enrollment](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [varchar](50) NULL,
- [LastName] [varchar](50) NULL,
- [Password] [nvarchar](30) NULL,
- [Email] [nvarchar](50) NULL,
- [Phone] [varchar](15) NULL,
- [SecurityAnwser] [nvarchar](50) NULL,
- [Gender] [varchar](15) NULL,
- PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- GO
STEP-2
Now write a stored procedure named as SP_EnrollDetail as below,
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
- create procedure [dbo].[SP_EnrollDetail]
- (
- @FirstName varchar(50)=NULL,
- @LastName varchar(50)=NULL,
- @Password varchar(50)=NULL,
- @Gender varchar(10)=NULL,
- @Email nvarchar(50)=NULL,
- @Phone varchar(15)=NULL,
- @SecurityAnwser nvarchar(50)=NULL,
- @status varchar(15)
- )
- as
- begin
- if @status='Insert'
- begin
- insert into Enrollment(FirstName,LastName,Password,Gender,Email,Phone,SecurityAnwser)values(@FirstName,@LastName,@Password,@Gender,@Email,@Phone,@SecurityAnwser)
- end
- end
Now, create another procedure named as sp_GetEnrollmentDetails to get the details in Admin Panel
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- create procedure [dbo].[sp_GetEnrollmentDetails]
- (@Email nvarchar(50))
- as
- begin
- select * from Enrollment where Email=@Email
- end
Now, let's come to the programming part of it using Visual Studio. I am using VS 2010 due to a specific problem, you can code in VS 2015 or further.
STEP-1
Create a Project in MVC then, create a class in the Model folder by right clicking. Name it Enroll. cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
-
- namespace PRIYANKAPROJECT.Models
- {
- public class Enroll
- {
- [Display(Name = "ID")]
- public int ID { get; set; }
-
- [Required(ErrorMessage = "Please enter FirstName")]
- [Display(Name = "FirstName")]
- public string FirstName { get; set; }
-
- [Required(ErrorMessage="Please enter LastName" )]
- [Display(Name = "LastName")]
- public string LastName { get; set; }
-
- [Required(ErrorMessage = "Please enter password")]
- [DataType(DataType.Password)]
- [StringLength(100, ErrorMessage = "Password \"{0}\" must have {2} character", MinimumLength = 8)]
- [RegularExpression(@"^([a-zA-Z0-9@*#]{8,15})$", ErrorMessage = "Password must contain: Minimum 8 characters atleast 1 UpperCase Alphabet, 1 LowerCase Alphabet, 1 Number and 1 Special Character")]
public string Password { get; set; }
-
- [Display(Name = "Confirm password")]
- [Required(ErrorMessage = "Please enter confirm password")]
- [Compare("Password", ErrorMessage = "Confirm password doesn't match, Type again !")]
- [DataType(DataType.Password)]
- public string Confirmpwd { get; set; }
- public Nullable<bool> Is_Deleted { get; set; }
-
- [Display(Name = "Gender")]
[Required(ErrorMessage = "Please Select the gender")]
public string Gender { get; set; }
-
- [Required]
- [RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "E-mail id is not valid")]
- public string Email { get; set; }
-
- [DataType(DataType.PhoneNumber)]
- [Display(Name = "Phone Number")]
- [Required(ErrorMessage = "Phone Number Required!")]
- [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",ErrorMessage = "Entered phone format is not valid.")]
- public string PhoneNumber { get; set; }
-
- [Required(ErrorMessage = "Please enter Security Answer")]
- [Display(Name = "Security Answer")]
- public string SecurityAnwser { get; set; }
-
- public List<Enroll> Enrollsinfo { get; set; }
-
- }
- }
STEP-2
Right click on Controller Class. Add a Controller named EnrollmentController
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using PRIYANKAPROJECT.Models;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
-
- namespace PRIYANKAPROJECT.Controllers
- {
- public class EnrollmentController : Controller
- {
- public string value = "";
-
- [HttpGet]
- public ActionResult Index()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Index(Enroll e)
- {
- if (Request.HttpMethod == "POST")
- {
- Enroll er = new Enroll();
- using (SqlConnection con = new SqlConnection("Data Source=PRIYANKA\\SQLEXPRESS;Integrated Security=true;Initial Catalog=Sample"))
- {
- using (SqlCommand cmd = new SqlCommand("SP_EnrollDetail", con))
- {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@FirstName", e.FirstName);
- cmd.Parameters.AddWithValue("@LastName", e.LastName);
- cmd.Parameters.AddWithValue("@Password", e.Password);
- cmd.Parameters.AddWithValue("@Gender", e.Gender);
- cmd.Parameters.AddWithValue("@Email", e.Email);
- cmd.Parameters.AddWithValue("@Phone", e.PhoneNumber);
- cmd.Parameters.AddWithValue("@SecurityAnwser", e.SecurityAnwser);
- cmd.Parameters.AddWithValue("@status", "INSERT");
- con.Open();
- ViewData["result"] = cmd.ExecuteNonQuery();
- con.Close();
- }
- }
- }
- return View();
- }
-
- }
- }
STEP-3
Right-click on Index() Action Method and add a view
- @model PRIYANKAPROJECT.Models.Enroll
-
- @{
- ViewBag.Title = "Index";
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>ENROLLMENT</title>
- <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"/>
- <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
- <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- <link href="../../Content/StyleSheet.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
- <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
- <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
- <script type="text/javascript" src="~/Scripts/passwordscheck.js"></script>
- <link href="~/Scripts/passwordscheck.css" rel="stylesheet" />
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
- </head>
- <body>
- <!------ Include the above in your HEAD tag ---------->
- @using (Html.BeginForm("Index", "Enrollment", FormMethod.Post))
- {
- <div class="container register">
- <div class="row">
- <div class="col-md-3 register-left">
- <img src="https://image.ibb.co/n7oTvU/logo_white.png" alt=""/>
- <h3>Welcome</h3>
- <p>This Example is for learning Basic Login and Registration Using ADO.NET in MVC.
- <br />Hope this will boast your Knowledge.</p>
- </div>
- <div class="col-md-9 register-right">
- <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist">
- <li class="nav-item">
- <a class="nav-link active" id="home-tab" data-toggle="tab" href="../Enrollment/Index" role="tab" aria-controls="home" aria-selected="true">Register</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" id="profile-tab" data-toggle="tab" href="../UserLogin/Index" role="tab" aria-controls="profile" aria-selected="false">Login</a>
- </li>
- </ul>
- <div class="tab-content" id="myTabContent">
- <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
- <h3 class="register-heading">Apply as a Employee</h3>
- <div class="row register-form">
- <div class="col-md-6">
- <div class="form-group">
- @Html.TextBoxFor(e => e.FirstName, new { @class = "form-control", placeholder = "First Name *" })
- @Html.ValidationMessageFor(e => e.FirstName)
- </div>
- <div class="form-group">
- @Html.TextBoxFor(e => e.LastName, new { @class = "form-control", placeholder = "Last Name *" })
- @Html.ValidationMessageFor(e => e.LastName)
- </div>
- <div class="form-group">
- @Html.PasswordFor(e => e.Password, new { id = "password", @class = "form-control", placeholder = "Password *" })
- <span id="result"></span>
- @Html.ValidationMessageFor(e => e.Password)
- </div>
- <div class="form-group">
- @Html.PasswordFor(e => e.Confirmpwd, new { @class = "form-control", placeholder = "Confirm Password *" })
- @Html.ValidationMessageFor(e => e.Confirmpwd)
- </div>
- <div class="form-group">
- <div class="maxl">
- @Html.RadioButtonFor(e => e.Gender, "Male", new { @class = "radio inline" })<span> Male </span>
- @Html.RadioButtonFor(e => e.Gender, "Female", new { @class = "radio inline" })<span>Female </span>
- </div>
- </div>
- </div>
- <div class="col-md-6">
- <div class="form-group">
- @Html.TextBoxFor(e => e.Email, new { @class = "form-control", placeholder = "Your Email *" })
- @Html.ValidationMessageFor(e => e.Email)
- </div>
- <div class="form-group">
- @Html.TextBoxFor(e => e.PhoneNumber, new { @class = "form-control", placeholder = "Your Phone *" })
- @Html.ValidationMessageFor(e => e.PhoneNumber)
-
- </div>
- <div class="form-group">
- <select class="form-control">
- <option class="hidden" selected disabled>Please select your Sequrity Question</option>
- <option>What is your Birthdate?</option>
- <option>What is Your old Phone Number</option>
- <option>What is your Pet Name?</option>
- </select>
- </div>
- <div class="form-group">
- @Html.TextBoxFor(e => e.SecurityAnwser, new { @class = "form-control",placeholder="`Answer *"})
- @Html.ValidationMessageFor(e => e.SecurityAnwser)
-
- </div>
- <input type="submit" class="btnRegister" value="Register"/>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <script type="text/javascript">
- $(function () {
- var msg = '@ViewData["result"]';
- if (msg == '1')
- {
- alert("User Details Inserted Successfully");
- window.location.href = "@Url.Action("Index", "Enrollment")";
- }
- });
- </script>
- }
- </div>
- }
- </body>
- </html>
Now build your project and run it. In Localhost run the page as
http://localhost:51320/Enrollment/Index, as you can see in the below screenshot.
Now, add the record into the form, data is saved in a database in the table below.
STEP-4
Now create a controller named as
UserLogin. You can write Controller Action() Method in the same
EmployeeController or you can write it separately. I have written it
separately.
Now add a view on the Index Action method of UserLogin Controller as
- @model PRIYANKAPROJECT.Models.Enroll
-
- @{
- ViewBag.Title = "Index";
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>ENROLLMENT</title>
- <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"/>
- <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
- <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
- <link href="../../Content/StyleSheet.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript">
-
- $(document).ready(function () {
- $.ajax({
-
- type: 'POST',
- URL: '/UserLogin/UserLogin',
- data: data,
- dataType: 'JSON',
- success: function (data) {
- datadata = data.status
- if (status == "1") {
- window.location.href = '@Url.Action("Index","UserLogin")';
- }
- }
- });
- });
- </script>
- </head>
-
- <body>
- <!------ Include the above in your HEAD tag ---------->
- @using (Html.BeginForm("Index", "UserLogin", FormMethod.Post))
- {
- @Html.AntiForgeryToken()
- <div class="container register">
- <div class="row">
- <div class="col-md-3 register-left">
- <img src="https://image.ibb.co/n7oTvU/logo_white.png" alt=""/>
- <h3>Welcome</h3>
- <p>This Example is for learning MVC Basic Login and Registration Using ADO.NET.</p>
- </div>
- <div class="col-md-9 register-right">
- <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist">
- <li class="nav-item">
- <a class="nav-link active" id="home-tab" data-toggle="tab" href="../Enrollment/Index" role="tab" aria-controls="home" aria-selected="true">Register</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" id="profile-tab" data-toggle="tab" href="../UserLogin/Index" role="tab" aria-controls="profile" aria-selected="false">Login</a>
- </li>
- </ul>
- <div class="tab-content" id="myTabContent">
- <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
- <h3 class="register-heading">Login as a Employee</h3>
- <div class="row register-form">
- <div class="col-md-6">
- <div class="form-group">
- @Html.TextBoxFor(e => e.Email, new { @class = "form-control", placeholder = "Your Email *" })
- @Html.ValidationMessageFor(e => e.Email)
- </div>
- <div class="form-group">
- @Html.PasswordFor(e => e.Password, new { id = "password", @class = "form-control", placeholder = "Password *" })
- <span id="result"></span>
- @Html.ValidationMessageFor(e => e.Password)
- </div>
- <div class="col-md-6">
- <input type="submit" class="btnLogin" value="Login"/>
- </div>
-
- </div>
-
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <script type="text/javascript">
- $(function () {
- var msg = '@ViewData["result"]';
- if (msg == '1')
- {
- alert("User Details Inserted Successfully");
- window.location.href = "@Url.Action("Index", "UserLogin")";
- }
- });
- </script>
- }
- </div>
- }
- </body>
- </html>
Now, Open this URL http://localhost:49629/UserLogin/Index for the login page or using the Login tab in the form.
After successful login, the dashboard is generated. I have already added Welcome() Action Method in UserLogin Controller.
Now, you can see the dashboard or Admin Panel as below with Logout functionality.
I hope you definitely learned from this project. If you have any queries regarding this project feel free to ask and I have already attached the Source Code of the Project file. I will definitely share if I added some more functionality in it in further blogs.
Take care of yourself and keep learning.
Thank you.