Thursday, 21 May 2015

How to create a login page using AngularJS in MVC4 application

Part 3 - How to create a login page using AngularJS in MVC4 application


INTRODUCTION

In this post, I would like to explain Part 3 - How to create a login page using AngularJS in MVC4 application. 
This is our third Post about AngularJS. Here I have explained a little about AngularJS and What we will learn in this section part by part. In Part1 of this post we configured AngularJS in MVC4 application. In this part (Part 3) I am going to explain how to create a login page using AngularJS in MVC4 application.

In Part 2 We used Get Method of AngularJS $http service for Fetch Data from Database. Here In this example We will see how we can use Post Method of AngularJS $http service for post data to the server.

STEPS :

STEP-1: CREATE TABLE INTO THE DATABASE.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used one tables as below

STEP-2: UPDATE ENTITY DATA MODEL.

Go to Solution Explorer > Open your Entity Data Model (here "MyModel.edmx") > Right Click On Blank area for Get Context Menu > Update Model From Database... > A popup window will come (Entity Data Model Wizard) > Select Tables > Finish.

STEP-3: CREATE A MODEL (CLASS).

Here I have created a Model in the Models folder. 
Go to Solution Explorer > Right Click on Models folder form Solution Explorer > Add > Class > Enter name > Add.

Here I have created a model (class) Named "LoginData". 
Write following code in this class. 

  1. namespace MVCWithAngularJs.Models
  2. {
  3. public class LoginData
  4. {
  5. public string Username { get; set; }
  6. public string Password { get; set; }
  7. }
  8. }

STEP-4: ADD NEW ACTION INTO YOUR CONTROLLER (HERE IN THE DATA CONTROLLER) FOR LOGIN AND RETURN USER DATA AS JSONRESULT FROM DATABASE.

Here I have added "UserLogin" Action into "DataController". Please write this following code 

  1. public JsonResult UserLogin(LoginData d)
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. var user = dc.Users.Where(a => a.Username.Equals(d.Username) && a.Password.Equals(d.Password)).FirstOrDefault();
  6. return new JsonResult { Data = user, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  7. }
  8. }

STEP-5: ADD A NEW JS FILE FOR ADD A NEW ANGULARJS CONTROLLER AND A FACTORY

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

Write following code in this file. 

  1. angular.module('MyApp') // extending from previously created angular module in the First Part
  2. .controller('Part3Controller', function ($scope, LoginService) {
  3. $scope.IsLogedIn = false;
  4. $scope.Message = '';
  5. $scope.Submitted = false;
  6. $scope.IsFormValid = false;
  7. $scope.LoginData = {
  8. Username: '',
  9. Password: ''
  10. };
  11.  
  12. //Check is Form Valid or Not // Here f1 is our form Name
  13. $scope.$watch('f1.$valid', function (newVal) {
  14. $scope.IsFormValid = newVal;
  15. });
  16. $scope.Login = function () {
  17. $scope.Submitted = true;
  18. if ($scope.IsFormValid) {
  19. LoginService.GetUser($scope.LoginData).then(function (d) {
  20. if (d.data.Username != null) {
  21. $scope.IsLogedIn = true;
  22. $scope.Message = "Successfully login done. Welcome " + d.data.FullName;
  23.  
  24. }
  25. else {
  26. alert('Invalid Credential!');
  27. }
  28. });
  29. }
  30. };
  31.  
  32. })
  33. .factory('LoginService', function ($http) {
  34. var fac = {};
  35. fac.GetUser = function (d) {
  36. return $http({
  37. url: '/Data/UserLogin',
  38. method: 'POST',
  39. data: JSON.stringify(d),
  40. headers: {'content-type':'application/json'}
  41. });
  42. };
  43. return fac;
  44. });

Here I have created an angular controller named "Part3Controller" and a Factory named "LoginService" with $http injected service. I have explained a little about AngularJS controller here , about Factory here and about $http here.

STEP-6: ADD NEW ACTION INTO YOUR CONTROLLER FOR GET THE VIEW FOR LOGIN.

Here I have added "Part3" Action into "Home" Controller. Please write this following code 

  1. public ActionResult Part3() // Login from Database
  2. {
  3. return View();
  4. }

STEP-7: ADD VIEW FOR THE ACTION & DESIGN.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 
Complete View 
  1. @{
  2. ViewBag.Title = "Part3";
  3. }
  4.  
  5. <style>
  6. input{
  7. padding:5px;
  8. border:1px solid #A5A5A5;
  9. }
  10. input.ng-dirty.ng-invalid {
  11. border:1px solid red;
  12. background-color:rgb(255, 244, 244);
  13. }
  14. .error {
  15. color:red;
  16. }
  17. </style>
  18.  
  19. <h2>Part3 - Create Login Page</h2>
  20.  
  21. <div ng-controller="Part3Controller">
  22. <form novalidate name="f1" ng-submit="Login()">
  23. <div style="color:rgb(142,2,2)">{{Message}}</div>
  24. <table ng-show="!IsLogedIn"> <!-- Here ng-show="!IsLogedIn" means I want to hide table after loged in-->
  25. <tr>
  26. <td>Username : </td>
  27. <td>
  28.  
  29. <!-- Here ng-class="Submitted?'ng-dirty':''" Means if submitted (clicked submit button) then make this dirty state
  30. for show red border-->
  31. <input type="text" ng-model="LoginData.Username" name="cUsername" ng-class="Submitted?'ng-dirty':''" required autofocus />
  32. <span class="error" ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required">Username required</span>
  33.  
  34. <!-- ng-show="(f1.cUsername.$dirty || Submitted) && f1.cUsername.$error.required" Means I want to show this span only when
  35. the control cUsername is invalid-->
  36. </td>
  37. </tr>
  38. <tr>
  39. <td>Password : </td>
  40. <td>
  41. <input type="password" ng-model="LoginData.Password" name="cPassword" ng-class="Submitted?'ng-dirty':''" required autofocus />
  42. <span class="error" ng-show="(f1.cPassword.$dirty || Submitted) && f1.cPassword.$error.required">Password required</span>
  43. </td>
  44. </tr>
  45. <tr>
  46. <td></td>
  47. <td>
  48. <input type="submit" value="Login" />
  49. </td>
  50. </tr>
  51. </table>
  52. </form>
  53. </div>
  54.  
  55.  
  56.  
  57. @section scripts{
  58. <script src="~/Scripts/AngularController/Part3Controller.js"></script>
  59. }

Here you can see I have used followings : 
  • ng-submit : ng-submit prevents the default action of form and binds angular function to onsubmit events. This is invoked when form is submitted means submit button is pressed.
  • ng-show : The ngShow allow us to display or hide different elements based on the expression provided to the ngShow attribute.
  • ng-model : ng-model has two-way data binding [$scope to View and View to $scope]. Its also has built-in validation and Keeping the state of the control. Based on the state its set related class to the element.
  • ng-class : Sometimes we need to change our view's CSS classes on-the-fly. Its allow us to dynamically set CSS classes based on Angular evaluated expressions
  • $dirty : This is a property of form elements and its True if user has already interacted with the form. There are many more properties like $pristine, $valid, $invalid, $submitted and $error.

STEP-8: RUN APPLICATION.

Related Posts:

0 comments: