AngularJS Tutorial for Login with MVC

Introduction

  • When selecting the latest technologies, several factors come into play, including how will these technologies will be integrated with our project.
  • This article solves the problem for beginners who start working with AngularJS and MVC.
  • Here I tell each and every aspect of the AnguarJS to use with what, why, and how.
         
Create Database and Tables
  • Firstly Create database named TestData.
  • After creating the database create a table with the name Logins.
        
  • Set the Id column as primary key and auto increment id in every table.
  • That's it with the database. 
Get the JS and CSS files from given links
To be familiar with the things Click Here

Let's start with the code  
  • Open the VS2012 ,Create New ASP.Net MVC4 Web Application and give the Name LoginAngularMvcApp.
  • Go to Models Folder in the solution explorer of visual studio.
  • Right click the Models folder and find ADD >>> ADO.NET Entity Data Model. Select ADO.NET Entity Data Model.
  • Provide the name LoginModel. After that pop up will appear .

        

  • Select generate from database and click next.

        

  • In the given box type entity name as SahilEntities and After that click New connection.

        
 

  •  Select Sql server authentication and fill the credentials like server name ,user name ,password,and then select your database from the database list.

                    

  • Check the checkboxes of tables and click on finish.
Create the LoginController by right clicking on the controller folder 
  • Change the Index ActionResult name from index to Login.This will return the Login View.
  • After that [HttpPost] Login method with Login class as parameter serves the purpose for actual operation of login.
  • Here we first check from the database that requesting user exists in the database or not.If exists than enteredpassword is compared with database password.
  • If exists return 0,-1 or userID.                   
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using BootstrapThemeAngular.Models;  
  7. using BootstrapThemeAngular.Utilities;  
  8. using System.Text;  
  9. using System.Web.Security;  
  10.   
  11. namespace BootstrapThemeAngular.Controllers  
  12. {  
  13.     public class LoginController : Controller  
  14.     {  
  15.           
  16.         // GET: /Login/  
  17.         public ActionResult Login()  
  18.         {  
  19.             return View();  
  20.         }  
  21.   
  22.         [HttpPost]  
  23.         public string Login(Login data)  
  24.         {  
  25.             bool isPasswordCorrect = false;  
  26.             string un = data.Username;  
  27.             string Password = data.Password;  
  28.             using (SahilEntities entity = new SahilEntities())  
  29.             {  
  30.                 var user = entity.Logins1.Where(u => u.UserName == un).FirstOrDefault();  
  31.                 if (user != null)  
  32.                 {  
  33.                     if (Password == user.Password)  
  34.                     {  
  35.                         Session["LoginID"] = user.ID;  
  36.                         Session["Username"] = user.Fname + ' ' + user.Lname;  
  37.                         return user.ID.ToString();  
  38.                     }  
  39.                     else  
  40.                     {  
  41.                         return "0";  
  42.                     }  
  43.                 }  
  44.                 else  
  45.                 {  
  46.                     return "-1";  
  47.                 }  
  48.             }  
  49.         }   
Add 3 files --> Module.js,Controller.js,Service.js in content folder
  • Here we register the module with the application.
  • Here myApp is the module name that we used with ng-app directive in HTML view.
  • In Module.js write the given code.         
  1. var app = angular.module("myApp", []); 
  • myCntrl is the controller name that is registered with the myApp module and used in HTML view with ng-controller directive.
  • $scope is used to refers to the application.Data passed to $scope in controller is accessible in view.
  • myService is the name of service that is used with controller to call the functions from server.
  • LoginCheck function get the username and password from $scope and store in the object variables.
  • UserLogin function from service is called that returns the response in form of values after that certain action performs.
  • Clearfields clear the HTML controls after login.
  • alertmsg hides the alert modal that displays alert messages.         
  1. app.controller("myCntrl"function ($scope, myService) {  
  2.   
  3. $scope.LoginCheck = function () {  
  4.         var User = {  
  5.             UserName: $scope.uName,  
  6.             Password: $scope.password  
  7.         };  
  8.         $("#divLoading").show();  
  9.         var getData = myService.UserLogin(User);  
  10.         getData.then(function (msg) {  
  11.             if (msg.data == "0") {  
  12.                 $("#divLoading").hide();  
  13.                 $("#alertModal").modal('show');  
  14.                 $scope.msg = "Password Incorrect !";  
  15.             }  
  16.             else if (msg.data == "-1") {  
  17.                 $("#divLoading").hide();  
  18.                 $("#alertModal").modal('show');  
  19.                 $scope.msg = "Username Incorrect !";  
  20.             }  
  21.             else {  
  22.                 uID = msg.data;  
  23.                 $("#divLoading").hide();  
  24.                 window.location.href = "/Home/Index";  
  25.             }  
  26.         });  
  27.         debugger;  
  28.     }  
  29.   
  30. function clearFields() {  
  31.         $scope.uName = '';        
  32.         $scope.uPwd = '';  
  33.     }  
  34.   
  35. });  
  1. $scope.alertmsg = function () {  
  2.         $("#alertModal").modal('hide');  
  3.     }; 
  • In Service.js write the given code.
  • myService is the name of the service registers with the myApp module.
  • $http is passed as parameter. $http serves the purpose for ajax call to the server.
  • In this service UserLogin function is used to call the Login method from server by providing url.
  • This method returns the response to the controller.      
  1. app.service("myService"function ($http) {  
  2.   
  3.  this.UserLogin = function (User) {  
  4.         var response = $http({  
  5.             method: "post",  
  6.             url: "/Login/Login",  
  7.             data: JSON.stringify(User),  
  8.             dataType: "json"  
  9.         });  
  10.         return response;  
  11.     }  
  12.   
  13. });  
Now write the code to display the view on screen
  • Write the code in Login.cshtml
  • In View HTML tag is used with the directive ng-app. ng-app calls the myApp module to initialize with this view.
  • After that all the css and script files are dropped in head tag.
  • ng-controller directive is used with the div tag to initialize with the controller we created.
  • <div class="container" ng-controller="myCntrl"> . Here ng-controller is a directive and myCntrl is the name of controller we specify in the controller.js file.
  • Alert modal is placed to display the messages for password or username incorrect.
  • In the container fluid class the panel is placed to put the controls on the panel.
  • CSS is applied to the panel for attractive look.
  • divLoading is used to just make the waiting time screen attractive.This serves for no other purpose.
  • Button placed after that to call login Method.Button contains ng-disabled directive ,use of this directive is untill,unless controls are not filled the Login button is disabled.
  • LoginCheck() function in ng-click directive calls the funtion from controller after click.      
  1. @{  
  2.     ViewBag.Title = "Login";  
  3. }  
  4.   
  5. <html ng-app="myApp">  
  6. <head>  
  7.     <title></title>  
  8.      <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  9.     <script src="~/Content/Angular/RegisterModule.js"></script>  
  10.     <script src="~/Content/Angular/RegisterService.js"></script>  
  11.     <script src="~/Content/Angular/RgstrController.js"></script>  
  12.     <script src="~/Content/Angular/dirPagination.js"></script>  
  13.   
  14. </head>  
  15. <body>  
  16.   
  17.     <div ng-controller="myCntrl">  
  18.         <h1>  
  19.           <img src="~/Content/images/Loginicon.png" /></h1>  
  20.         <br />  
  21.         <div id="alertModal" class="modal fade">  
  22.             <div class="modal-dialog">  
  23.                 <div class="modal-content">  
  24.                     <!-- dialog body -->  
  25.                     <div class="modal-body">  
  26.                         <button type="button" id="btn" value="Close" class="close" data-dismiss="modal">×</button>  
  27.                         {{msg}}  
  28.                     </div>  
  29.                     <!-- dialog buttons -->  
  30.                     <div class="modal-footer">  
  31.                         <button type="button" ng-click="alertmsg()" class="btn btn-primary">OK</button>  
  32.                     </div>  
  33.                 </div>  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="container-fluid">  
  38.             <div class="panel panel-success" style="width: 50%;">  
  39.                 <div class="panel-heading">Login</div>  
  40.                 <div class="panel-body" style="box-shadow: -6px 2px 46px 7px #888888; padding: 20px;">  
  41.                     <form name="loginForm"  novalidate>  
  42.                         <div class="form-horizontal">  
  43.                             <div class="form-group">     
  44.                                 <div class="row">  
  45.                                     <div class="col-md-3" style="text-align: right;">  
  46.                                         Username :  
  47.                                     </div>  
  48.                                     <div class="col-md-6">  
  49.                                         <div class="input-group">  
  50.                                             <input type="text" class="form-control" id="Uname" placeholder="Username" ng-model="uName" name="Username" required autofocus />  
  51.                                             <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>  
  52.                                         </div>                                      
  53.                                     </div>  
  54.                                 </div>  
  55.                             </div>  
  56.   
  57.                             <div class="form-group">    
  58.                                 <div class="row">  
  59.                                     <div class="col-md-3" style="text-align: right;">  
  60.                                         Password :  
  61.                                     </div>  
  62.                                     <div class="col-md-6">  
  63.                                         <div class="input-group">  
  64.                                             <input type="password" class="form-control" id="password" placeholder="Password" ng-model="password" name="Password" required autofocus />  
  65.                                             <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>  
  66.                                         </div>                                       
  67.                                     </div>                                     
  68.                             <div class="form-group">  
  69.                                 <div class="row">  
  70.                                     <div class="col-md-6">  
  71.                                         <div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">  
  72.                                             <p style="position: absolute; top: 30%; left: 45%; color: White;">  
  73.                                                 please wait...<img src="~/Content/images/load.png">  
  74.                                             </p>  
  75.                                         </div>  
  76.                                     </div>  
  77.                                 </div>  
  78.                             </div>  
  79.   
  80.                             <div class="form-group">  
  81.                                 <div class="row">  
  82.                                     <div class="col-md-5" style="text-align: right;">  
  83.                                         <button id="btnLogin" type="submit" class="btn btn-success" ng-disabled="!(password && uName)" ng-click="LoginCheck()">Login</button>  
  84.                                     </div>                                      
  85.                                 </div>  
  86.                             </div>  
  87.                         </div>  
  88.                     </form>  
  89.                 </div>  
  90.             </div>  
  91.         </div>  
  92.     </div>  
  93. </body>  
  94. </html>   
Apply CSS and Scripts file
  • Find BundleConfig.cs in App_Start folder.
  • Here we register the css snd js files to use with the layout page.  
  1. public static class BundleConfig  
  2.    {  
  3.        public static void RegisterBundles(BundleCollection bundles)  
  4.        {  
  5.            RegisterStyleBundles(bundles);  
  6.            RegisterJavascriptBundles(bundles);  
  7.        }  
  8.   
  9.        private static void RegisterStyleBundles(BundleCollection bundles)  
  10.        {  
  11.            bundles.Add(new StyleBundle("~/css")  
  12.                            .Include("~/Content/bootstrap.css")  
  13.                            .Include("~/Content/carousel.css")  
  14.                            .Include("~/Content/site.css"));  
  15.        }  
  16.   
  17.        private static void RegisterJavascriptBundles(BundleCollection bundles)  
  18.        {  
  19.            bundles.Add(new ScriptBundle("~/js")  
  20.                            .Include("~/Scripts/jquery-{version}.js")  
  21.                            .Include("~/Scripts/jquery-ui-{version}.js")  
  22.                            .Include("~/Scripts/bootstrap.js"));  
  23.        }  
  24.    } 

Start by creating your own app.

Read more articles on AngularJS: