Introduction
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 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 the 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} characters", MinimumLength = 8)]
[RegularExpression(@"^([a-zA-Z0-9@*#]{8,15})$", ErrorMessage = "Password must contain: Minimum 8 characters, at least 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))
{
<p class="container register">
<p class="row">
<p 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 boost your Knowledge.
</p>
</p>
<p 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>
<p class="tab-content" id="myTabContent">
<p class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<h3 class="register-heading">Apply as a Employee</h3>
<p class="row register-form">
<p class="col-md-6">
<p class="form-group">
@Html.TextBoxFor(e => e.FirstName, new { @class = "form-control", placeholder = "First Name *" })
@Html.ValidationMessageFor(e => e.FirstName)
</p>
<p class="form-group">
@Html.TextBoxFor(e => e.LastName, new { @class = "form-control", placeholder = "Last Name *" })
@Html.ValidationMessageFor(e => e.LastName)
</p>
<p 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)
</p>
<p class="form-group">
@Html.PasswordFor(e => e.Confirmpwd, new { @class = "form-control", placeholder = "Confirm Password *" })
@Html.ValidationMessageFor(e => e.Confirmpwd)
</p>
<p class="form-group">
<p 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>
</p>
</p>
</p>
<p class="col-md-6">
<p class="form-group">
@Html.TextBoxFor(e => e.Email, new { @class = "form-control", placeholder = "Your Email *" })
@Html.ValidationMessageFor(e => e.Email)
</p>
<p class="form-group">
@Html.TextBoxFor(e => e.PhoneNumber, new { @class = "form-control", placeholder = "Your Phone *" })
@Html.ValidationMessageFor(e => e.PhoneNumber)
</p>
<p 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>
</p>
<p class="form-group">
@Html.TextBoxFor(e => e.SecurityAnwser, new { @class = "form-control", placeholder = "Answer *" })
@Html.ValidationMessageFor(e => e.SecurityAnwser)
</p>
<input type="submit" class="btnRegister" value="Register" />
</p>
</p>
</p>
</p>
</p>
</p>
</p>
<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>
}
</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 to the form. Data is saved in a database in the table below.

Step 4. Now create a controller named UserLogin. You can write the Controller Action() Method in the same EmployeeController, or you can write it separately. I have written it separately.



suraj chavanPosted Mar 16, 2023, 9:46 AM
- $exception {"Could not find stored procedure 'SP_EnrollDetail'."} System.Data.SqlClient.SqlException
ajay chauhanPosted Feb 28, 2023, 4:04 PM
How i set the authentication. After login on browser back button i go back to login. How can i protect this.
shah krushilPosted Feb 7, 2023, 8:53 AM
Hi UserDetails.cs and Register.cs are Not Working So Please Check
Rahul KumarPosted Jul 22, 2022, 3:55 PM
One script not working showing error. The Userdetails.cs and Register.cs classes are not there.
gaurav humbarfkarPosted Apr 14, 2022, 1:10 PM
Hii Priyanka Singh why you are using below ajax method its look like there is no use for that $(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")'; } } }); });
narayanarao pPosted Dec 4, 2021, 4:54 AM
The Userdetails.cs and Register.cs classes are not properly updated in the attached source code of project file.
Saladino MiladPosted Oct 17, 2021, 9:45 AM
Userdetails.cs & Register.cs classes not uploaded with the application, please upload all thing and database structure :) :)
Rabiha ShaheenPosted Oct 14, 2021, 11:10 PM
The Userdetails.cs and Register.cs classes are not there.
Sumit PatilPosted Jul 2, 2021, 6:21 AM
Simple and easy to understand . thanks.
amit rajPosted Jun 18, 2021, 1:57 PM
This code is not down,loading