In this post we will see how we can create MVC Login form using Angular JS. The login credentials will be stored in MS SQL Database.
Angular JS will be handling the “HttpPost” request from the MVC Views and passing the values(class object) to the ASP.NET MVC Controller. So let’s begin.
The database:
Create a database with name “AngularApp”. And a table with name “tblUsers” with columns shown in the picture below.
Database script:
Create database [AngularApp]
USE [AngularApp]
GO
/****** Object: Table [dbo].[tblUsers] Script Date: 1/1/2019 6:05:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblUsers](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[EmailId] [nvarchar](50) NOT NULL,
[Passcode] [nvarchar](50) NOT NULL,
[OnDate] [datetime] NULL CONSTRAINT [DF__tblUsers__OnDate__7D78A4E7] DEFAULT (getdate()),
[UserRole] [nvarchar](50) NULL CONSTRAINT [DF__tblUsers__UserRo__7E6CC920] DEFAULT ('User'),
CONSTRAINT [PK__tblUsers__7C8480AE] 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
-------------------------------------------
create procedure sp_login
(
@EmailId nvarchar(50), @Passcode nvarchar(50)
)
as begin
Select * from tblUsers where EmailId=@EmailId and Passcode=@Passcode Collate sql_latin1_general_cp1_cs_as
end
Next in your ASP.NET MVC Project create a folder named “Angular”. In this folder create a Javascript file with name “login.js” and save angular.min.js file in this folder.
- Project > Angular(folder name) > login.js
- Project > Angular(folder name) > angular.min.js (download link).
Edit the login.js file as shown below. This will be Angular JS file which will be handling HttpPost request from MVC views and posting the data (class object) to the server (MVC controller) and showing the respective HTML page (MVC View page) to our user.
login.js:
var app = angular.module('loginapp', []);
app.controller("LoginController", function ($scope, $http) {
$scope.btntext = "Login";
$scope.login = function () {
$scope.btntext = "Please wait....";
$http({
method: "POST",
url: '/User/Login',
data: $scope.Users
}).then(function (response) {
var k = JSON.parse(JSON.stringify(response.data));
alert(k.message);
if (k.message == 'Login Successful') {
window.location = '/Dashboard/';
$scope.btntext = "Success!";
}
else
$scope.btntext = "Login";
}, function (error) {
var k = JSON.parse(JSON.stringify(response.data));
alert(k.message);
$scope.btntext = "";
});
}
})
In project model folder create a class as shown below
Project > Models > Users.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AngularLogin.Models
{
public class Users
{
public int userid { get; set; }
public string username { get; set; }
public string emailid { get; set; }
public string password { get; set; }
public string role { get; set; }
public string message { get; set; }
}
}
This class will be passed to our MVC controller using Angular JS script. And returned.
Add ConnectionString in Project’s web.config file:
ConnectionString:
<connectionStrings>
<add name="con" connectionString="Data Source=192.168.0.192;Initial Catalog=AngularApp;User ID=sa;Password=789;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Create a MVC controller with name User and edit it following
Project > Controller > UserController.cs:
using AngularLogin.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace AngularLogin.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
public string Login(Users user)
{
user = DoLogin(user);
if (user.message == "Login Successful")
{
Session["emailuser"] = user.emailid;
Session["role"] = user.role;
Session["userid"] = user.userid;
Session["username"] = user.username;
}
var json = new JavaScriptSerializer().Serialize(user);
return json;
}
public Users DoLogin(Users user)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_login";
cmd.Parameters.AddWithValue("@EmailId", user.emailid);
cmd.Parameters.AddWithValue("@Passcode", user.password);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
user.role = reader["UserRole"].ToString();
user.userid = Convert.ToInt32(reader["UserId"].ToString());
user.message = "Login Successful";
user.username = reader["UserName"].ToString();
}
else
user.message = "Invalid Credentials";
}
catch (Exception ex)
{
user.message = ex.Message.ToString();
}
return user;
}
}
}
Add a MVC View for the Index method by right-clicking on the method name > Add View
Project > Views > User > Index.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<style>
.logindiv {
margin-top: 10%;
width: 100%;
}
body {
margin: 0 !important;
padding: 0 !important;
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif
}
.loginbtn {
background-color: #2A3132;
padding: 5px;
color:#fff;
}
</style>
<title>User Login</title>
</head>
<body ng-app="loginapp" ng-controller="LoginController">
<div style="background-color:#2A3132;width:100%;padding:1px;">
<center><h2 style="color:white">User Login</h2></center>
</div>
<div class="logindiv">
<center>
<table>
<tr>
<td>
Email:
</td>
<td>
<input type="text" ng-model="Users.emailid" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td><input type="password" ng-model="Users.password" /></td>
</tr>
<tr>
<td class="table table-condensed" colspan="2">
<input class="btn btn-primary loginbtn" type="button" value="{{btntext}}" ng-click="login()" />
</td>
</tr>
</table>
</center>
</div>
<script src="~/angular/angular.min.js"></script>
<script src="~/Angular/login.js"></script>
</body>
</html>
AngularJS Login form in MVC ASP.NET Forms C#:
Add another MVC controller with name “Dashboard” and edit it as below
Project > Controller > DashboardController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularLogin.Controllers
{
public class DashboardController : Controller
{
// GET: Dashboard
public ActionResult Index()
{
String email = this.HttpContext.Session["emailuser"].ToString();
ViewBag.UserEmail = this.HttpContext.Session["emailuser"].ToString();
ViewBag.UserRole = this.HttpContext.Session["role"].ToString();
ViewBag.UserId = this.HttpContext.Session["userid"].ToString();
ViewBag.UserName = this.HttpContext.Session["username"].ToString();
return View();
}
}
}
Same. Add a MVC View for the Index() method by right-clicking on the method name > Add View
Project > Views > Dashboard > Index.cshtml:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<style>
body {
margin: 0 !important;
padding: 0 !important;
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif
}
</style>
<title>Dashboard</title>
</head>
<body>
<div style="background-color:#2A3132;width:100%;padding:1px;">
<center><h2 style="color:white">Dashboard</h2></center>
</div>
<div style="padding:10px;">
User Id: @ViewBag.UserId<br /><br />
Name: @ViewBag.UserName<br /><br />
Email: @ViewBag.UserEmail<br /><br />
Role: @ViewBag.UserRole<br /><br />
</div>
</body>
</html>
Now run your project.
See Also:
ASP.NET MVC Add and Retrieve Cookies Example.
MVC Login Page using SQL Database and Razor
Binding Angular JS Bind HTML table from SQL in ASP.NET MVC C#
Bind|Populate ASP.NET MVC C# Dropdownlist from SQL
C# ASP.NET MVC Add and Retrieve Cookies
Creating a Login Page in ASP.NET MVC C# using SQL table and Razor
Creating a Registration page in ASP.NET C#
How to solve Could not find stored procedure ‘sp_login’?
Sorry, I have missed it.Here you go (I updated the database script also for the post):
create procedure sp_login
(
@EmailId nvarchar(50), @Passcode nvarchar(50)
)
as begin
Select * from tblUsers where EmailId=@EmailId and Passcode=@Passcode Collate sql_latin1_general_cp1_cs_as
end
Pingback: Angularjs Login System - Login Portal
Pingback: Angularjs Login Controller - Login Portal