Agung Code
20 min readJul 6, 2020

ASP NET : Create Login Form Using SQL Command

In this article, I will give you a way to create a User Login and Password on ASP NET. Where the user must verify before logging in and there is a password recovery feature if the password is forgotten.
In order to facilitate the discussion, the Great Guide broke it into several core topics, namely:

Login Form ASP NET MVC Using SQLCommand
Login Form ASP NET MVC Using SQLCommand
  1. Login form
  2. Password Encryption
  3. Registration form
  4. Email notification
  5. Generate User verification link
  6. Forget Password
  7. Generate OTP
  8. Change Password

Create Project ASP NET

Step 1
Create a Table Registration Table in SQL Server with the database name UserLogin.

CREATE TABLE [dbo].[UserM](  
[UserId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Password] [nvarchar](250) NOT NULL,
[EmailVerification] [bit] NULL,
[ActivetionCode] [uniqueidentifier] NULL,
[OTP] [nvarchar](4) NULL,
CONSTRAINT [PK_UserM] PRIMARY KEY CLUSTERED
(
[UserId] 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

Step 2

Open Visual Studio 2012 and create a new “ASP NET MVC Web Application” project with the name “UserLoginSQLCommand”.

Use the Empty Template.

Step 3

Add Bootstrap and Font-Awesome to the Project using NuGet

Step 4

Add a Common Model to hold the value for the JSON value (BaseResult and AjaxResult).

Step 5

Create a Model UserM.cs into the Models> DBContext folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UserLoginSQLCommand.Models.DBContext
{
public class UserM
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public Nullable<bool> EmailVerification { get; set; }
public Nullable<System.Guid> ActivetionCode { get; set; }
public string OTP { get; set; }
}
}

Step 6

Create a Layout view as below,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Styles.Render("~/Content/Bootstrap/css")
@Scripts.Render("~/Content/Bootstrap/js")
@*@Scripts.Render("~/bundles/jqueryval")*@
<script src="@Url.Content("~/Scripts/jquery.validate.js")" ></script>
@*<script src="@Url.Content("~/Content/Bootstrap/js/jquery.min.js")" ></script>*@
@*<link rel="stylesheet" href="@Url.Content("~/Content/Bootstrap/css/bootstrap.css")" />*@
</head>
<body style="padding-top: 70px;">
@*@if (CurrentName!="Login"){
*@<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
@Html.ActionLink("Whiteopen", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
<button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div id="navbar" class="navbar-collapse collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
<li class="nav-item"><a class="nav-link" href="#">About</a></li>
<li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
</ul>
</div>
</nav>
@*}*@
<div class="container body-content">
@RenderBody()
<hr />
@*<footer class="panel-footer">
@RenderSection("footer", true)
</footer>*@
@*@if (CurrentName!="Login"){
*@<footer class="panel-footer">
<div class="bg-secondary" style="height:100%">
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-12 col-12 text-white">
<div class="row p-3">
<div class="col-md-6 col-12">
<p class="m-0">All Right Reserved 2020 - <a href="http://www.agungpanduan.com" target="_blank">agungpandun.com</a></p>
</div>
@*<div class="col-md-6 col-12 footer-icon text-right">
<i class="fa fa-twitter"></i>
<i class="fa fa-instagram"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-linkedin"></i>
<i class="fa fa-youtube"></i>
<i class="fa fa-vimeo"></i>
</div>*@
</div>
</div>
</div>
</div>
</div>
</div>
</footer>
@* }*@
</div>

@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/jquery")
@*<script src="jquery-3.0.0.min.js"></script>
<script src="popper.min.js"></script>
<script src="bootstrap.min.js"></script>*@
@RenderSection("scripts", required: false)
</body>
</html>

Step 7

We will make a simulation that to enter the member page, we must login first and the member page contains important tables as below,

@using System;

<style>
.text-large {
text-transform: uppercase;
background: linear-gradient(to right, #30CFD0 0%, #330867 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 500%;
font-family: 'Poppins', sans-serif;
}
.row.no-gutter {
margin-left: 0px;
margin-right: 0;
margin-top: 0;
margin-bottom:0;
width:100%;
}
.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
padding-right: 10px;
padding-left: 10px;
padding-top: 10px;
padding-bottom:10px;
}
input[name='need']:disabled {
background: red !important;
color:black !important;
}

</style>

<div class="container">
<div class="row no-gutter">
<div class="col-md-6" style="padding-top:13px;">
<div class="row no-gutter"><i class="fa fa-user col-md-3">
<label for="inputEmail" class="col-md-4 col-form-label text-success" >Name</label></i>
<div class="col-md-8">
<input type="text" class="form-control" id="inputName">
</div>
</div>
<div class="row no-gutter"><i class="fa fa-venus-mars col-md-3">
<label for="cmbGender" class="col-md-4 col-form-label text-success">Gender</label></i>
<div class="col-md-8">
<select class="form-control" id="cmbGender">
<option selected="selected" value="">--Please Choose--</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<p class="float-right text-large"><span id="furnace_no">CLASS 1 </span></p>
</div>
</div>
<div class="row" >
<div class="bg-primary text-white text-center col-md-12">
<h4>Type 1</h4>
</div>
</div>
<div class="row no-gutter">
<div class="container">
<table class="table">
<thead>
<tr class="table-primary">
<th class="text-center grid-checkbox-col" rowspan="2">
<input class="grid-checkbox" type="checkbox" id="checkall" />
</th>
<th rowspan="1">Name</th>
<th rowspan="1">Gender</th>
<th rowspan="1">Email</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Male"/>
</td>
<td>Agung Panduan</td>
<td>Male</td>
<td>admincool@agungpanduan.com</td>
</tr>
<tr class="table-success">
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Male"/>
</td>
<td>Joe</td>
<td>Male</td>
<td>adminjoe@e-pandu.com</td>
</tr>
<tr>
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Female"/>
</td>
<td>Sinta</td>
<td>Female</td>
<td>john@example.com</td>
</tr>
<tr class="table-success">
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Female"/>
</td>
<td>Mary</td>
<td>Female</td>
<td>mary@example.com</td>
</tr>
<tr>
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Male"/>
</td>
<td>Dooley</td>
<td>Male</td>
<td>july@example.com</td>
</tr>
<tr class="table-success">
<td class="text-center grid-checkbox-col">
<input name="chkRow" type="checkbox" class="grid-checkbox grid-checkbox-body"
data-ClassId="" value="Female"/>
</td>
<td>Lisa</td>
<td>Female</td>
<td>bo@example.com</td>
</tr>

</tbody>
</table>
</div>
</div>
<div class="row no-gutter">
<div class="col-md-12">
<div class="text-right">
<button id="btnSave" type="button" class="btn btn-sm btn-success">Save</button>
<button id="btnSkip" type="button" class="btn btn-sm btn-primary">Skip</button>
</div>
</div>
</div>
<br />
</div>
@*@section footer{
<div class="bg-secondary" style="height:100%">
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-12 col-12 text-white">
<div class="row p-3">
<div class="col-md-6 col-12">
<p class="m-0">All Right Reserved 2020 - <a href="http://www.agungpanduan.com" target="_blank">agungpandun.com</a></p>
</div>
<!--<div class="col-md-6 col-12 footer-icon text-right">
<i class="fa fa-twitter"></i>
<i class="fa fa-instagram"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-linkedin"></i>
<i class="fa fa-youtube"></i>
<i class="fa fa-vimeo"></i>
</div>-->
</div>
</div>
</div>
</div>
</div>
</div>
}*@

<script type="text/javascript">
$(document).ready(function () {
$("#checkall").click(function () {
$(".grid-checkbox").prop("checked", $("#checkall").is(":checked"));
});

$(".grid-checkbox").click(function () {
$("#checkall").prop("checked", $('.grid-checkbox:not(#checkall)').not(':checked').length == 0);
});
});
</script>

@if (Request.IsAuthenticated)
{
<a href='@Url.Action("LogOut", "Login")' onclick='navigate(this.href);'>
<input style="float: right;" type="button" value='Logout' />
</a>
}

Even if you type Member URL in the browser, you cannot see the member page above without going through the login page first

Login Form

Step 8

We need to specify the connection string under the <configuration> tag for the database in the Web.config file which is not in views. The problem is there are two Web.config.

<connectionStrings>
<add name="SqlConnectionString" connectionString="Server=localhost;Database=TEST;User ID=sa;Password=admin;Trusted_Connection=false;MultipleActiveResultSets=true;Max Pool Size=1000;Timeout=300000" providerName="System.Data.SqlClient"/>
</connectionStrings>

Step 9

Create the Login Model UserLogin.cs in the models folder

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace UserLogin.Models
{
public class Userlogin
{
[Display(Name = "User Email ID")]
[Required(AllowEmptyStrings = false, ErrorMessage = "User Email Id Required")]

public string EmailId { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Password Required")]
public string Password { get; set; }

[Display(Name = "Remember Me")]
public bool Rememberme { get; set; }
}
}

Step 10

Create View Login.cshtml and _ViewLogin.cshtml in the models> Login folder

Login.cshtml

@{
Layout = null;
}
@Scripts.Render("~/Content/Bootstrap/js")
@Scripts.Render("~/bundles/jquery")
<!------ Include the above in your HEAD tag ---------->

@*<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>*@
@Styles.Render("~/Content/Bootstrap/css")
@Styles.Render("~/Content/FontAweSome/css")
<link rel="stylesheet" href="@Url.Content("~/Content/AnotherCss/Login.css")" />

<!--Custom styles-->
<link rel="stylesheet" type="text/css" href="styles.css">
@*</head>
<body>*@
<style>
p
{
color:white;
}

</style>
<div class="container">
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-header">
<h3>Sign In</h3>
<div class="d-flex justify-content-end social_icon">
<span><i class="fa fa-facebook-square"></i></span>
<span><i class="fa fa-google-plus-square"></i></span>
<span><i class="fa fa-twitter-square"></i></span>
</div>
</div>
<div class="card-body">
@Html.Partial("_ViewLogin")
</div>
<div class="card-footer">
<div class="d-flex justify-content-center links">
Don't have an account?<a href="javascript:void(0)" onClick="CallRegisterView();"> Sign Up</a>
</div>
<div class="d-flex justify-content-center">
<a href="javascript:void(0)" onClick="CallResetView();">Forgot your password?</a>
<!--LANGSUNG KE CONTROLLER-->
@*<a href='@Url.Action("ForgetPassword", "Login")' onclick='navigate(this.href);'>Forgot your password?</a>*@
</div>
</div>
</div>
</div>
</div>@*
@*</body>
</html>*@

<script type="text/javascript">
$(document).ready(function () {

});

$("#btnLogin").click(function () {
$("#divusername").empty();
$("#divpassword").empty();
if ($("#txtusername").val() == "") {
$("<p>Input username</p>").appendTo($("#divusername"));

} else if ($("#txtpassword").val() == "") {
$("<p>Input password</p>").appendTo($("#divpassword"));
}
else { Callajaxlogin(); }
});

function Callajaxlogin() {
var params = new Object();
params.EmailId = $("#txtusername").val(),
params.Password = $("#txtpassword").val()
$.ajax({
type: "POST",
url: "@Url.Content("~/Login/Login")",
contentType: 'application/json',
dataType: 'json',
traditional: true,
data: JSON.stringify(params),
success: function (returnResult) {
if (returnResult.Result == "SUCCESS") {
window.location = returnResult.RedirectURL;
}
else {
$("#pesanerror").html(returnResult.ErrMesgs[0]);
}

},
error: function (data) {
//showErrorMesgGrowl('Login failed');
}
});
}
</script>

_ViewLogin.cshtml

<form>
<p id="pesanerror"></p>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<input type="text" class="form-control" placeholder="username" id="txtusername"/>
</div>
<div id="divusername"></div>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="password" id="txtpassword"/>
<p id="pesanerrorpass"></p>
</div>
<div id="divpassword"></div>
<div class="row align-items-center remember">
<input type="checkbox">Remember Me
</div>
<div class="form-group">
<button id="btnLogin" type="button" value="Login" class="btn float-right login_btn">Login</button>
</div>
</form>

Step 11

Now, we will add the JsonResult method. In this method, there will be a checking process whether the User is in the database or not and generates a cookie value for the Remember Me checkbox.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using UserLoginSQLCommand.Models.Common;
using System.Net;
using System.Net.Mail;
using UserLoginSQLCommand.Models.DBContext;

namespace UserLoginSQLCommand.Controllers
{
public class LoginController : Controller
{
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
//
// GET: /Login/

public ActionResult Index()
{
return View("Login");
}

public JsonResult Login(string EmailId, string Password)
{
AjaxResult ajaxResult = new AjaxResult();
IList<string> errMesgs = new List<string>();
Int32 count;
var _passWord = UserLoginSQLCommand.Models.encryptPassword.textToEncrypt(Password);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(1) FROM [dbo].[UserM] Where 1=1" +
"AND [Email] = '" + EmailId + "' AND [Password]='" + _passWord + "' AND [EmailVerification]=1";
SqlCommand command = new SqlCommand(query, connection);
count = (Int32)command.ExecuteScalar();
//count =
connection.Close();
}

UserLoginSQLCommand.Models.UserLogin a = new Models.UserLogin();
if (count > 0)
{
int timeout = a.Rememberme? 60 : 5; // Timeout in minutes, 60 = 1 hour.
var ticket = new FormsAuthenticationTicket(EmailId, false, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
//return View("Index", "_LayoutAfterLogin");
//return RedirectToAction("Index", "Member");

//return Redirect("Member/Index");
//return PartialView("~/Views/Shared/_LayoutAfterLogin.cshtml");

ajaxResult.Result = AjaxResult.VALUE_SUCCESS;
ajaxResult.RedirectURL = "Member";
}
else {
//ViewBag.Message = "Email yang kamu gunakan tidak ditemukan atau belum verfikasi email";
ajaxResult.Result = ajaxResult.ValueError;
ajaxResult.ErrMesgs = new string[] { string.Format("{0} : {1}", "Warning", "The e-mail you are using is not found or e-mail verification") };
if (errMesgs.Count > 0)
{
ajaxResult.Result = AjaxResult.VALUE_ERROR;
ajaxResult.ErrMesgs = errMesgs.ToArray();
}
}
return Json(ajaxResult);
}
}
}

Step 12

Users who have access will be directed to the homepage after successfully logging in. But before entering the User’s Home, check Authorization first for security purposes. For this reason, MemberController.cs is added.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace UserLoginSQLCommand.Controllers
{
public class MemberController : Controller
{
//
// GET: /Member/
[HttpGet]
[Authorize]
public ActionResult Index()
{
return View();
}

[Authorize]
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Login");
}
}
}

You can see here that the User has successfully logged in and the resulting cookie is found in the browser.

Step 13

Now, we need the Action logout method to log out the application. To log out, add the logout method to the controller, as shown below.

[Authorize]
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Login");
}

Step 14

For the login process, we use form authentication mode, so we need a few changes as below in web.config. Here you can see setting the authentication mode and setting the default login URL.

<authentication mode=”Forms”>

<forms cookieless=”UseCookies” loginUrl=”Login”></forms>

</authentication>

Save it in <system.web>

Encrypt Password

For security reasons, passwords are always stored in encrypted format. So, we will add a class that will change the password to the encryption format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace UserLogin.Models
{
public static class encryptPassword
{
public static string textToEncrypt(string paasWord)
{
return Convert.ToBase64String(System.Security.Cryptography.SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(paasWord)));
}
}
}

Registration form

The model used for registration is UserM which is stored in the DBContext folder

Step 15

Add the JsonResult Register Method to LoginController.cs. In this method there will be a process to check whether the email is already in the database or not, generate the activation code, encrypt the password that is created, insert new data into the table using SQLCommand and send email verification.

public JsonResult Register(UserM data)
{
AjaxResult ajaxResult = new AjaxResult();
IList<string> errMesgs = new List<string>();
Int32 count;
// email not verified on registration time
data.EmailVerification = false;
//it generate unique code
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(1) FROM [dbo].[UserM] Where 1=1" +
"AND [Email] = '" + data.Email + "'";
SqlCommand command = new SqlCommand(query, connection);
count = (Int32)command.ExecuteScalar();
//count =
connection.Close();
}

if (count == 0)
{
data.ActivetionCode = Guid.NewGuid();
data.Password = UserLoginSQLCommand.Models.encryptPassword.textToEncrypt(data.Password);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO [dbo].[UserM]([FirstName],[LastName],[Email],[Password],[EmailVerification],[ActivetionCode]) VALUES(@FirstName,@LastName,@Email,@Password,@EmailVerification,@ActivetionCode) ";
cmd.Parameters.AddWithValue("@FirstName", data.FirstName);
cmd.Parameters.AddWithValue("@LastName", data.LastName);
cmd.Parameters.AddWithValue("@Email", data.Email);
cmd.Parameters.AddWithValue("@Password", data.Password);
cmd.Parameters.AddWithValue("@EmailVerification", 0);
cmd.Parameters.AddWithValue("@ActivetionCode", data.ActivetionCode);
cmd.ExecuteNonQuery();
}
connection.Close();
}

SendEmailVerificationToUser(data.Email, data.ActivetionCode.ToString());

ajaxResult.Result = AjaxResult.VALUE_SUCCESS;
//ajaxResult.RedirectURL = "lokasi...";
}
else
{
ajaxResult.Result = ajaxResult.ValueError;
ajaxResult.ErrMesgs = new string[] { string.Format("{0} : {1}", "Warning", "The email used is already registered") };
if (errMesgs.Count > 0)
{
ajaxResult.Result = AjaxResult.VALUE_ERROR;
ajaxResult.ErrMesgs = errMesgs.ToArray();
}
}

return Json(ajaxResult);
}

Step 16

In this login project, I use the process of changing the login page to the register using the html () method so that it doesn’t create a new file for the register page. For that, you just need to add some functions to the Login.cshtml file.

Registration Form ASP NET MVC Using SQLCommand
Registration Form ASP NET MVC Using SQLCommand
function CallRegisterView() {
$(".card-body").html('<form id="myform">'
+ '<div class="input-group form-group" >'
+ ' <div class="input-group-prepend">'
+ ' <span class="input-group-text"><i class="fa fa-user"></i></span>'
+ ' </div>'
+ ' <input type="text" class="form-control" placeholder="firstname" id="txtfirstname"/>'
+ '</div>'
//+ '<div id="divfirstname"></div>' +
+ '<div class="input-group form-group" >'
+ ' <div class="input-group-prepend">'
+ ' <span class="input-group-text"><i class="fa fa-user"></i></span>'
+ ' </div>'
+ ' <input type="text" class="form-control" placeholder="lastname" id="txtlastname"/>'
+ '</div>'
//+ '<div id="divlastname"></div>' +
+ '<div class="input-group form-group" >'
+ ' <div class="input-group-prepend">'
+ ' <span class="input-group-text"><i class="fa fa-user"></i></span>'
+ ' </div>'
+ ' <input type="text" class="form-control" placeholder="email" id="txtemail" class="required email"/>'
+ '</div>'
//+ '<div id="divemail"></div>' +
+ '<div class="input-group form-group" >'
+ ' <div class="input-group-prepend">'
+ ' <span class="input-group-text"><i class="fa fa-key"></i></span>'
+ ' </div>'
+ ' <input type="password" class="form-control" placeholder="password" id="txtcreatepassword"/>'
+ '</div>'
//+ '<div id="divcreatepassword"></div>' +
+ '<div class="input-group form-group" >'
+ ' <div class="input-group-prepend">'
+ ' <span class="input-group-text"><i class="fa fa-key"></i></span>'
+ ' </div>'
+ ' <input type="password" class="form-control" placeholder="confirm password" id="txtconfirmpassword"/>'
+ '</div>'
+ '<div id="divregistererror"></div>'
+ '<div class="form-group">'
+ '<button id="btnRegister" type="button" value="Register" class="btn float-right login_btn">Register</button>'
+ '</div>'
+ '</form>');

// $(".card").css({ "height": $(".card-body").height() + ($(".card").height() - $(".card-footer").height() - $(".card-header").height()) });

$(".card-footer").html('<div class="d-flex justify-content-center links">' +
'Do have an account?<a href="javascript:void(0)" onClick="LoginBack();">Login</a>' +
'</div>'); //+
//'<div class="d-flex justify-content-center">' +
// '<a href="javascript:void(0)" onClick="CallResetView();">Forgot your password?</a>' +
//'</div>');

$(".card").css({ "height": $(".card").height() + ($(".card-body").height() / 2) });
}

function LoginBack() {
window.location = 'login';
}

$(".card-body").on('click', "#btnRegister", function () {
$("#divregistererror").empty();
if ($("#txtfirstname").val() == "") {
$("<p>Input firstname</p>").appendTo($("#divregistererror"));
}
else if ($("#txtlastname").val() == "") {
$("<p>Input lastname</p>").appendTo($("#divregistererror"));
}
else if ($("#txtemail").val() == "") {
$("<p>Input email</p>").appendTo($("#divregistererror"));
}
else if ($("#txtcreatepassword").val() == "") {
$("<p>Input password</p>").appendTo($("#divregistererror"));
}
else if ($("#txtconfirmpassword").val() == "") {
$("<p>Input confirm password</p>").appendTo($("#divregistererror"));
}
else if ($("#txtcreatepassword").val() != $("#txtconfirmpassword").val()) {
$("<p>Password and confirm password are different</p>").appendTo($("#divregistererror"));
}
else {
CallRegister();
alert("a");
}
});

function CallRegister() {
var params = new Object();
var data = new Object();

//alert($("#txtusername").val());
data.FirstName = $("#txtfirstname").val();
data.LastName = $("#txtlastname").val();
data.Email = $("#txtemail").val();
data.Password = $("#txtcreatepassword").val();
params.data = data;

$.ajax({
type: "POST",
url: "@Url.Content("~/Login/Register")",
contentType: 'application/json',
dataType: 'json',
traditional: true,
data: JSON.stringify(params),
success: function (returnResult) {
if (returnResult.Result == "SUCCESS") {
$("<p>Please Check the Email Inbox for the Email Verification Process</p>").appendTo($("#divregistererror"));
//window.location = returnResult.RedirectURL;
}
else {
$("<p>" + returnResult.ErrMesgs[0] + "</p>").appendTo($("#divregistererror"));
}

},
error: function (data) {
//showErrorMesgGrowl('Login failed');
}
});
}

Email notification

Now, we will show how to send a confirmation email after registering. When sending there will be a verification link by email.

Step 17

Adding References in controllers,

using System.Net;

using System.Net.Mail;

Step 18

and add the SendEmailVerificationToUser() method to LoginController.cs

public void SendEmailVerificationToUser(string emailId, string activationCode)
{
var GenarateUserVerificationLink = "/Login/UserVerification/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);

var fromMail = new MailAddress("oneagungpanduan@gmail.com", "Agung Panduan"); // set your email
var fromEmailpassword = "yourpassword email"; // Set your password
var toEmail = new MailAddress(emailId);

var smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);

var Message = new MailMessage(fromMail, toEmail);
Message.Subject = "Registration Completed-Demo";
Message.Body = "<br/> Your registration completed succesfully." +
"<br/> please click on the below link for account verification" +
"<br/><br/><a href=" + link + ">" + link + "</a>";
Message.IsBodyHtml = true;
smtp.Send(Message);
}

Step 19

Activate the use of a gmail account for Visual Studio by logging into the Gmail account that you use and then Manage your Google Account> Security> Access less secure applications. Click the Activate access button (not recommended).

After successful registration, an email with a verification link is sent.

After successful registration, an email with a verification link is sent.

Verification from Email Account

When you register by email there is always an order to verify the email ownership of the email. Then a verification method is needed,

#region Verification from Email Account.
public ActionResult UserVerification(string id)
{
Int32 count;

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(1) FROM [dbo].[UserM] Where 1=1" +
"AND [ActivetionCode] = '" + id + "'";
SqlCommand command = new SqlCommand(query, connection);
count = (Int32)command.ExecuteScalar();
//count =
connection.Close();
}

if (count == 0)
{
ViewBag.Message = "Invalid Request...Email not verify";
//ViewBag.Status = false;
}
else
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE [dbo].[UserM] SET [EmailVerification]=1 WHERE [ActivetionCode] = @ActivetionCode";
cmd.Parameters.AddWithValue("@ActivetionCode", id);
cmd.ExecuteNonQuery();
}
connection.Close();
}

ViewBag.Message = "Email Verification completed";
}

return View("UserVerification");
}
#endregion

Generate User verification link

Not only is the addition of the ActionResult method but also a message is needed indicating that the email verification has been performed.

@{  
ViewBag.Title = "UserVerification";
}

<h2>User Verification Process</h2>

<div class="alert-success">
<strong>Message: </strong> @ViewBag.Message, please click here to Login @Html.ActionLink("Login", "Login", "Register")
</div>

When you click the link in the email we can see the debugging results as below,

ASP NET User Verification Mail
ASP NET User Verification Mail

After verifying, the table update process will occur in the EmailVerification column, which was 0 to 1.

Forget Password

Not everyone remembers the username and password that was created earlier on a particular site. The average web application always provides the Forget Password feature, this feature is very helpful for users if they forget their password.

Step 20

Add the View ActionResult ForgetPassword method to LoginController.cs and the JsonResult method to set the “Forget Password”. Using this method, we will generate an OTP and then send an email to the user with a Password change URL. In this method, we will also check whether the user’s email id is correct or not.

public JsonResult ForgetPassword(UserM data)
{
AjaxResult ajaxResult = new AjaxResult();
IList<string> errMesgs = new List<string>();
Int32 count;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(1) FROM [dbo].[UserM] Where 1=1" +
"AND [Email] like '%" + data.Email + "'";
SqlCommand command = new SqlCommand(query, connection);
count = (Int32)command.ExecuteScalar();
//count =
connection.Close();
}

if (count == 0)
{
ajaxResult.Result = ajaxResult.ValueError;
ajaxResult.ErrMesgs = new string[] { string.Format("{0} = {1}", "Warning", "The email you are using is incorrect") };
if (errMesgs.Count > 0)
{
ajaxResult.Result = AjaxResult.VALUE_ERROR;
ajaxResult.ErrMesgs = errMesgs.ToArray();
}
//"EMAILNOTEXIST"
}
else {
// Genrate OTP
string OTP = GeneratePassword();

data.ActivetionCode = Guid.NewGuid();
data.OTP = OTP;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//CARA 1
//string query = "UPDATE [dbo].[UserM] SET [OTP] = '" + data.OTP + "' WHERE [Email]='" + data.Email + "'";
//
//SqlCommand command = new SqlCommand(query, connection);
//try
//{
// command.ExecuteNonQuery();
//}
//catch (SqlException ex)
//{
//
//}

//CARA 2
using (SqlCommand cmd = connection.CreateCommand()) {
cmd.CommandText = "UPDATE [dbo].[UserM] SET [OTP] = @otp WHERE [Email]=@email";
cmd.Parameters.AddWithValue("@otp", data.OTP);
cmd.Parameters.AddWithValue("@email", data.Email);
cmd.ExecuteNonQuery();
}
connection.Close();
}
ForgetPasswordEmailToUser(data.Email, data.ActivetionCode.ToString(), data.OTP);

ajaxResult.Result = AjaxResult.VALUE_SUCCESS;
//ajaxResult.RedirectURL = "lokasi...";
}

return Json(ajaxResult);
}

public string GeneratePassword()
{
string OTPLength = "4";
string OTP = string.Empty;

string Chars = string.Empty;
Chars = "1,2,3,4,5,6,7,8,9,0";

char[] seplitChar = { ',' };
string[] arr = Chars.Split(seplitChar);
string NewOTP = "";
string temp = "";
Random rand = new Random();
for (int i = 0; i < Convert.ToInt32(OTPLength); i++)
{
temp = arr[rand.Next(0, arr.Length)];
NewOTP += temp;
OTP = NewOTP;
}
return OTP;
}

public void ForgetPasswordEmailToUser(string emailId, string activationCode, string OTP)
{
var GenarateUserVerificationLink = "/Login/ChangePasswordView/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);

var fromMail = new MailAddress("oneagungpanduan@gmail.com", "Agung Kasep"); // set your email
var fromEmailpassword = "yourpassword"; // Set your password
var toEmail = new MailAddress(emailId);

var smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);

var Message = new MailMessage(fromMail, toEmail);
Message.Subject = "Password Reset-Demo";
Message.Body = "<br/> Your registration completed succesfully." +
"<br/> please click on the below link for account verification" +
"<br/><br/><a href=" + link + ">" + link + "</a>" +
"<br/>OTP for password change: " + OTP;
Message.IsBodyHtml = true;
smtp.Send(Message);
}

Step 21

Like the Registration Form, even in the Forget Password we use the replacement method html (), so we just need to add a new function to Login.cshtml

function myFunction(){
function CallResetView() {
//$(".card-body").html('Html.Partial("_ViewResetPassword").ToString()'
$(".card-body").html(
'<form>' +
'<p id="pesanerror"></p>'+
'<div class="input-group form-group" >'+
' <div class="input-group-prepend">'+
' <span class="input-group-text"><i class="fa fa-user"></i></span>'+
' </div>'+
' <input type="text" class="form-control" placeholder="username" id="txtusername"/>'+
'</div>'+
'<div id="divusername"></div>'+
'<div class="form-group">'+
' <button id="btnReset" type="button" value="Login" class="btn float-right login_btn">Reset Password</button>' +
//' <input id="test" type="button" value="aa" />'+
'</div>' +
'</form>');

$(".card-footer").html('<div class="d-flex justify-content-center links">'+
'Dont have an account?<a href="javascript:void(0)" onClick="CallRegister();">Sign Up</a>' +
'</div>'+
'<div class="d-flex justify-content-center">'+
'<a href="javascript:void(0)" onClick="LoginBack();">Login</a>'+
'</div>');

}

$(".card-body").on('click', "#btnReset", function () {
$("#divusername").empty();
if ($("#txtusername").val() == "") {
$("<p>Input username</p>").appendTo($("#divusername"));
}
else { CallResetPassword(); }
});

function CallResetPassword() {
var params = new Object();
var data = new Object();

//alert($("#txtusername").val());
data.Email = $("#txtusername").val();
params.data = data;

$.ajax({
type: "POST",
url: "@Url.Content("~/Login/ForgetPassword")",
contentType: 'application/json',
dataType: 'json',
traditional: true,
data: JSON.stringify(params),
success: function (returnResult) {
if (returnResult.Result == "SUCCESS") {
$("<p>Please Check Email Inbox</p>").appendTo($("#divusername"));
//window.location = returnResult.RedirectURL;
}
else {
$("#pesanerror").html("");
}

},
error: function (data) {
//showErrorMesgGrowl('Login failed');
}
});
}

Now, run the application and don’t forget to press the Forget Password button and fill in the email that was used to register.

The email obtained after Reset Password contains a link that must be visited to log in along with the OTP sent by the web application.

If the link sent by the web application is clicked by the user it will go to the Change Password view. To make a password change, an OTP is sent to the email.

Change Password

Step 22

Create the ChangePassword.cshtml view in the Login folder.

ASP NET Change Password View
ASP NET Change Password View
@{
Layout = null;
}
@Scripts.Render("~/Content/Bootstrap/js")
@Scripts.Render("~/bundles/jquery")
<!------ Include the above in your HEAD tag ---------->

@*<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>*@
@Styles.Render("~/Content/Bootstrap/css")
@Styles.Render("~/Content/FontAweSome/css")
<link rel="stylesheet" href="@Url.Content("~/Content/AnotherCss/Login.css")" />

<!--Custom styles-->
<link rel="stylesheet" type="text/css" href="styles.css">
@*</head>
<body>*@
<style>
p
{
color:white;
}
.card{
height: 450px;
margin-top: auto;
margin-bottom: auto;
width: 400px;
background-color: rgba(0,0,0,0.5) !important;
}

</style>
<div class="container">
<div class="d-flex justify-content-center h-100">
<div class="card">
<div class="card-header">
<h3>Change Password</h3>
</div>
<div class="card-body">
<form>
<p id="pesanerror"></p>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<input type="text" class="form-control" placeholder="Email" id="txtusername"/>
</div>
<div id="divusername"></div>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="text" class="form-control" placeholder="OTP" id="txtOTP"/>
@*<p id="pesanerroruser"></p>*@
</div>
<div id="divOTP"></div>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="password" id="txtpassword"/>
<p id="pesanerrorpass"></p>
</div>
<div id="divpassword"></div>
<div class="input-group form-group" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="confirm password" id="txtcopassword"/>
<p id="pesanerrorcopass"></p>
</div>
<div id="divcopassword"></div>
<div class="row align-items-center remember">
<input type="checkbox">Remember Me
</div>
<div class="form-group">
<button id="btnChangePassword" type="button" value="ChangePassword" class="btn float-right login_btn">Change Password</button>
</div>
</form>
</div>
</div>
</div>
</div>@*
@*</body>
</html>*@

<script type="text/javascript">
$(document).ready(function () {

});

$("#btnChangePassword").click(function () {
$("#divOTP").empty();
$("#divpassword").empty();
$("#divcopassword").empty();
if ($("#txtusername").val() == "") {
$("<p>Input Email</p>").appendTo($("#divusername"));

} else if ($("#txtOTP").val() == "") {
$("<p>Input OTP</p>").appendTo($("#divOTP"));

} else if ($("#txtpassword").val() == "") {
$("<p>input password</p>").appendTo($("#divpassword"));
}
else if ($("#txtcopassword").val() == "") {
$("<p>input confirm password</p>").appendTo($("#divcopassword"));
}
else if ($("#txtcopassword").val() != $("#txtpassword").val()) {
$("<p>Different Password and Confirm Password</p>").appendTo($("#divcopassword"));
}
else { CallajaxChangePassword(); }
});

function CallajaxChangePassword() {
var params = new Object();
params.Email = $("#txtusername").val(),
params.OTP = $("#txtOTP").val(),
params.Password = $("#txtcopassword").val()
$.ajax({
type: "POST",
url: "@Url.Content("~/Login/ChangePassword")",
contentType: 'application/json',
dataType: 'json',
traditional: true,
data: JSON.stringify(params),
success: function (returnResult) {
//
if (returnResult.Result == "SUCCESS") {
window.location = window.location.origin +'/'+returnResult.RedirectURL;
}
else {
$("#pesanerror").html(returnResult.ErrMesgs[0]);
}

},
error: function (data) {
//showErrorMesgGrowl('Login failed');
}
});
}

</script>

Step 23

Add the JsonResult ChangePassword Method to LoginController.cs. In this method there will be a process to check whether the email is already in the database or not, generate the activation code, encrypt the password that is created, Update data into the table using SQLCommand and send email Change Password Detail.

public ActionResult ChangePasswordView()
{
return View("ChangePassword");
}


#region Change Password from Email Account.
public JsonResult ChangePassword(UserM data)
{
AjaxResult ajaxResult = new AjaxResult();
IList<string> errMesgs = new List<string>();
Int32 count;

using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT COUNT(1) FROM [dbo].[UserM] Where 1=1" +
"AND [Email]='" + data.Email + "' AND [OTP] = '" + data.OTP + "'";
SqlCommand command = new SqlCommand(query, connection);
count = (Int32)command.ExecuteScalar();
//count =
connection.Close();
}

if (count != 0)
{
var passwordbeforeencryp = data.Password;
data.Password = UserLoginSQLCommand.Models.encryptPassword.textToEncrypt(data.Password);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "UPDATE [dbo].[UserM] SET [Password]=@Password WHERE [Email]=@Email AND [OTP] = @OTP";
cmd.Parameters.AddWithValue("@Email", data.Email);
cmd.Parameters.AddWithValue("@OTP", data.OTP);
cmd.Parameters.AddWithValue("@Password", data.Password);
cmd.ExecuteNonQuery();
}
connection.Close();
}

SendChangePasswordToUser(data.Email, passwordbeforeencryp);
ajaxResult.Result = AjaxResult.VALUE_SUCCESS;
ajaxResult.RedirectURL = "Login";
}
else
{
ajaxResult.Result = ajaxResult.ValueError;
ajaxResult.ErrMesgs = new string[] { string.Format("{0} : {1}", "Warning", "The email you are using is incorrect") };
if (errMesgs.Count > 0)
{
ajaxResult.Result = AjaxResult.VALUE_ERROR;
ajaxResult.ErrMesgs = errMesgs.ToArray();
}
}

return Json(ajaxResult);
}
#endregion


public void SendChangePasswordToUser(string emailId, string password)
{

var GenarateUserVerificationLink = "/Login/";
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);

var fromMail = new MailAddress("oneagungpanduan@gmail.com", "Agung Kasep"); // set your email
var fromEmailpassword = "yourpassword"; // Set your password
var toEmail = new MailAddress(emailId);

var smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);

var Message = new MailMessage(fromMail, toEmail);
Message.Subject = "Change Password Completed-Demo";
Message.Body = "<br/> Change Password completed succesfully." +
"<br/> please click on the below link for login" +
"<br/><br/><a href=" + link + ">" + link + "</a>" +
"<br/> Your New Password: " + password;
Message.IsBodyHtml = true;
smtp.Send(Message);
}

The email obtained after Change Password contains a link that must be visited to log in along with the New Password sent by the web application.

This is how to create ASP NET: login form using SQLCommand along with the registration process, email notification to email, forget password, and change password. If you need an example for ASP .NET Login form using the Entity Framework, you can visit the site agungcode.com

Download File Project ASP NET Login Form

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Agung Code
Agung Code

Written by Agung Code

0 Followers

Programmer, System Analyst, Blogger, Content Writer

No responses yet

Write a response