Login Form In AngularJS And ASP.NET MVC

Hello guys, how are you? As per your request, I am going to make a login page in AngularJS and ASP. NET.

I am trying to make this article as simple as I can .Hope you like it. Your valuable feedback is always welcome.Thanks.

Let's start.

Please follow these steps to make this application.

Step 1

Create an empty MVC project

First, open your Visual Studio -> File -> New -> Project -> ASP.NET Web Application and click OK. Now, select MVC and OK.

Now, you have created the basic project structure.

You can go though the screenshot given below for help.





You will have the Directory given below.

Step 2

Install Angular package

Install the Angular package in your project, as shown in the screenshot given below.



Step 3

In Views folder loginpage, paste the code given below in login.cshtml.

  1. @{  
  2.     ViewBag.Title = "Login Using Angular";  
  3. }  
  4. <h2>Login Using Angular</h2>  
  5.   
  6. <div ng-controller="LoginController">  
  7.     <form name="myForm" novalidate ng-submit="LoginForm()">  
  8.         <div style="color:green">{{msg}}</div>  
  9.         <table ng-show="!IsLoggedIn" class="table table-horizontal">  
  10.             <tr>  
  11.                 <td>Email/UserName :</td>  
  12.                 <td>  
  13.                     <input type="email" ng-model="UserModel.Email" name="UserEmail" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>  
  14.                     <span style="color:red" ng-show="(myForm.UserEmail.$dirty || Submited ) && myForm.UserEmail.$error.required">Please enter Email</span>  
  15.                     <span style="color:red" ng-show="myForm.UserEmail.$error.email">Email is not valid</span>  
  16.                 </td>  
  17.             </tr>  
  18.             <tr>  
  19.                 <td>Password :</td>  
  20.                 <td>  
  21.                     <input type="password" ng-model="UserModel.Password" name="UserPassword" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>  
  22.                     <span style="color:red" ng-show="(myForm.UserPassword.$dirty || Submited) && myForm.UserPassword.$error.required">Password Required</span>  
  23.                 </td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td></td>  
  27.                 <td>  
  28.                     <input type="submit" value="submit" class="btn btn-success" />  
  29.                 </td>  
  30.             </tr>  
  31.         </table>  
  32.     </form>  
  33. </div>  
  34. @section scripts{  
  35.     <script src="~/Scripts/LoginController.js"></script>  
  36. }   

We have to create a JavaScript login controller and added its reference, as shown below.

  1. <script src="~/Scripts/LoginController.js"></script>  

Step 4

Add Javascript Controllor

Create an Angular module in Module.js file and add the code given below. 

  1. (function () {  
  2.     var myApp = angular.module("myApp",[]);  
  3. })();  

Now, add another script file for Angular controller and Factory method.

Right click on Scripts folder --> add LoginController.js and write the code given below. 

  1. angular.module('myApp').controller('LoginController'function ($scope, LoginService) {  
  2.   
  3.         //initilize user data object  
  4.         $scope.LoginData = {  
  5.             Email: '',  
  6.             Password:''  
  7.         }  
  8.         $scope.msg = "";  
  9.         $scope.Submited = false;  
  10.         $scope.IsLoggedIn = false;  
  11.         $scope.IsFormValid = false;  
  12.   
  13.         //Check whether the form is valid or not using $watch  
  14.         $scope.$watch("myForm.$valid"function (TrueOrFalse) {  
  15.             $scope.IsFormValid = TrueOrFalse;   //returns true if form valid  
  16.         });  
  17.   
  18.         $scope.LoginForm = function () {  
  19.             $scope.Submited = true;  
  20.             if ($scope.IsFormValid) {  
  21.                 LoginService.getUserDetails($scope.UserModel).then(function (d) {  
  22.                     debugger;  
  23.                     if (d.data.Email != null) {  
  24.                         debugger;  
  25.                         $scope.IsLoggedIn = true;  
  26.                         $scope.msg = "You successfully Loggedin Mr/Ms " +d.data.FullName;  
  27.                     }  
  28.                     else {  
  29.                         alert("Invalid credentials buddy! try again");  
  30.                     }  
  31.                 });  
  32.             }  
  33.         }  
  34.     })  
  35.     .factory("LoginService"function ($http) {  
  36.         //initilize factory object.  
  37.         var fact = {};  
  38.         fact.getUserDetails = function (d) {  
  39.             debugger;  
  40.             return $http({  
  41.                 url: '/Home/VerifyUser,  
  42.                 method: 'POST',  
  43.                 data:JSON.stringify(d),  
  44.                 headers: { 'content-type''application/json' }  
  45.             });  
  46.         };  
  47.         return fact;  
  48.     });   

Step 5

Add New Action Method in HomeController to verifyuser. 

  1. public ActionResult VerifyUser (UserModel obj)  
  2.         {  
  3.             DatabaseEntities db = new DatabaseEntities();  
  4.             var user = db.Users.Where(x => x.Email.Equals(obj.Email) && x.Password.Equals(obj.Password)).FirstOrDefault();  
  5.             return new JsonResult {Data=user,JsonRequestBehavior=JsonRequestBehavior.AllowGet };  
  6.         }   

Step 6

Add a Model Class to Solution

Right click Models --> Add --> Class and name it UserModel.cs.

You can add usermodel, as shown below. 

  1. namespace LoginUsingAngular.Models  
  2. {  
  3.     public class UserModel  
  4.     {  
  5.         public string Email { get; set; }  
  6.         public string Password { get; set; }  
  7.     }  
  8. }   

Take a look at what the ng-Model, ng-show and ng-submit means, which is used in login.cshtml view given above.

  • ng-Model
    ngModel is an Angular Directive. It is used for two way binding data from view to controller and controller to view.

  • ng-show
    ngShow allows to display or hide the elements, which are based on the expression provided to ngShow attribute.

  • ng-submit
    ng-submit prevents the default action of form and binds Angular function to onsubmit events. This is invoked when the form is submitted.

  • $dirty
    It is an Angular built in property. It will be true, if the user interacts with the form, else it will be false.

There are many validation properties in Angular like $invalid,$submitted,$pristine,$valid and $error.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now