Loading, please wait...

A to Z Full Forms and Acronyms

Create Login Page using AngularJS in Asp.net MVC

Here I will explain How to create login page using AngularJS in Asp.net MVC application.

Introduction:

Today in this article, I will explain How to create a login page using AngularJS in ASP.Net MVC.

In this article, I have to use Ado.net for database operations and view engine as a razor.

Follow these steps in order to implement “Create login form using AngularJS in Asp.net MVC”

 

Step1: Create New Project.

 Go to File > New > Project > Web > Asp.net MVC web Application> Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty template > then click to ok

 

Step2: Create a table and Stored procedure in the database.

In this example, I have created following table and stored procedure for creating a login form.

CREATE TABLE [dbo].[tbl_registration] (

    [Sr_no]    INT            IDENTITY (1, 1) NOT NULL,

    [Email]    NVARCHAR (100) NULL,

    [Password] NVARCHAR (MAX) NULL,

    [Name]     VARCHAR (MAX)  NULL,

    [Address]  NVARCHAR (MAX) NULL,

    [City]     NVARCHAR (MAX) NULL,

    CONSTRAINT [PK_tbl_registration] PRIMARY KEY CLUSTERED ([Sr_no] ASC)

);

 

The design of table looks like this

 

 

 Now I have to create a stored procedure for fetching the record on the behalf of their email and password.

Create proc Sp_User_login

@Email nvarchar(200),

@Password nvarchar(200),

@Isvalid bit out

as

begin

Set @Isvalid=(Select Count(Email) from tbl_registration where Email=@Email and Password=@Password)

End

 

Step3: Add Connection string in web.config file

 Here I have to add connection string in ‘web.config’ file under Configuration section as follows

 

<connectionStrings>

    <add name="con" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

Step4: Create a controller.

Go to Solutions Explorer > right click on controller folder > Add Controller > Enter Controller name > Select template “empty MVC Controller   ” > Add.

Here I have created a controller “HomeController”

 

 Step5: Create Model for user Login

Add model class for email and password under model folder.

 this class contains following properties:

public class user

    {

        public string email { get; set; }

        public string password { get; set; }

    }

 

Step6: Create a class for Database operation.

Here in this example, I have used Ado.net as database operation so we need to create a class for all database operations. Here I have created ‘db.cs’ class.

Go to Solutions Explorer > right click on project solution> Add New Folder > Enter Folder name (Here I rename it as ‘database_Access_Layer’) > right click on folder > Add new class.

 

Now write the following code snippet given below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.SqlClient;

using System.Data;

using System.Configuration;

using AnguarLogin.Models;

namespace AnguarLogin.database_Access_Layer

{

    public class db

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

 

        public int userlogin(user us)

        {

            SqlCommand com = new SqlCommand("Sp_User_login", con);

            com.CommandType = CommandType.StoredProcedure;

            com.Parameters.AddWithValue("@Email",us.email);

            com.Parameters.AddWithValue("@Password",us.password);

            SqlParameter oblogin = new SqlParameter();

            oblogin.ParameterName = "@Isvalid";

            oblogin.Direction = ParameterDirection.Output;

            oblogin.SqlDbType = SqlDbType.Bit;

            com.Parameters.Add(oblogin);

            con.Open();

            com.ExecuteNonQuery();

            int res = Convert.ToInt32(oblogin.Value);

            con.Close();

            return res;

        }

    }

} 

 

In the above class, I have created a function for authenticating the user on the behalf of their email and password. This function taking the parameter as user class that contains properties like email and password and return the result as an integer value, If email and password are correct then it returns 1 otherwise 0.

 

Step7: Add methods in the controller.

I have created following methods in HomeController that has following code snippet:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using AnguarLogin.Models;

using System.Data;

namespace AnguarLogin.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        database_Access_Layer.db dblayer = new database_Access_Layer.db();

        public ActionResult Index()

        {

            return View();

        }

        public ActionResult dashboard()

        {

            return View();

        }

 

        public JsonResult userlogin(user us)

        {

            string  result = Convert.ToString(dblayer.userlogin(us));

 

            if (result=="1")

            {

                Session["user"] = us.email;

            }

            else

            {

                result = "Email or Password is wrong";

               

            }

            return Json(result,JsonRequestBehavior.AllowGet);

        }

 

    }

}

 

In above code, I have created JSON return types method that taking the parameter as email and password and then pass these values into the "userlogin" function of "db" class.

 

Step8: Add New JS file for AngularJS Controller and AngullarJS library file

Go to Solution Explorer > Right Click on the folder (where you want to save your AngularJS controller JS file, here I have created a folder named "AngularController"  under scripts Folder) > Add > Select Javascript file > Enter name > Add.

 

Now write the following code snippet

var app = angular.module('homeapp', []);

app.controller("HomeController", function ($scope,$http) {

    $scope.btntext = "Login";

    $scope.login = function () {

        $scope.btntext = "Please wait..!";

        $http({

            method: "POST",

            url: '/Home/userlogin',

            data: $scope.user

        }).success(function (d) {

            $scope.btntext = 'Login';

            if (d==1) {

                window.location.href = '/Home/dashboard';

            }

            else {

                alert(d);

            }

            $scope.user = null;

        }).error(function () {

            alert('failed');

        })

    }

 

})

 

Here I have created an Angular controller named as ‘HomeController’ with parameter $http and $scope

$http: $http is an AngularJS service for reading data from remote servers. It makes a request to the server and returns a response.

$Scope: $Scope is the binding part between the HTML (view) and the JavaScript (controller). It is an object with the available properties and methods. $Scope is available for both the view and the controller.

Here login function transfer to dashboard page when email and password is correct otherwise I show alert message that email or password is wrong

 

Step9: Add view and design.

Right Click on Action Method > Add View > Enter View Name (Here I add Index) > Select View Engine (Razor) > Add.

It has following code and design.

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body ng-app="homeapp" ng-controller="HomeController">

    <div>

        <span>Email:    </span><input type="text" ng-model="user.email" />

        <br />

        <br />

        <span>Password: </span><input type="password" ng-model="user.password" />

        <br />

        <br />

        <input type="button" value="{{btntext}}" ng-click="login()" />

    </div>

    <script src="~/script/angular.min.js"></script>

    <script src="~/script/AngularController/Angularhome.js"></script>

</body>

</html>

 

In the above code, ng-model is used to bind the user class properties and ng-click for trigger login function on the click of Login button.

 

Step 10: Run Application.

We have done all steps, now it’s time to run the application

 

 

Thanks ..!

 

If you have any problem and face any difficulty then Share your experiences with us in the comments below!

Like this post? Don’t forget to share it!

 

 

 

 

A to Z Full Forms and Acronyms

Related Article