Thursday, December 10, 2015

Create a Login Page in Angular Js with MVC

In this article I am going to create a Login Page in MVC using Angular JS.

Step 1

Go to Visual Studio Menu File->New-Project (Click on "Project" Menu Item). the out put will look like



Step 2

After Clicking on project Menu item a new window will be open and its output look like


now select ASP.NET MVC4 Web Application and rename your solution name to "LoginPageMVCWithAngularJS" and click on "OK"  button.

Step 3

After Complete Step 2 a new window will be open. select "Basic" template and  click on "OK" Button, output will look like



Step 4

Now right click at solution explorer  Click on "Manage NuGet Packages.."



Click on "Manage NuGet Packages.." After clicking on it a window will be open , type in search box "angularjs" and click on install to searched angular js item, output is



Step 5

After Installing angularjs click on close button


Step 6

At the Solution explorer  in Script Floder , you may see angular js file has loaded.
Now I edited "_Layout.cshtml" in "Views->Shared" folder.

_Layout.cshtml


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
   
</head>
    @* Here  ng-app="MyApp" is used for auto-bootstrap an AngularJS application. here ng-app="MyApp" means <body> element is the owner
    of AngularJS application*@
<body ng-app="MyApp">
    
    <div style="height:1px; clear:both;"></div>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @* Add Angular Library Here *@
    @Scripts.Render("~/bundles/angular")
    <script src="~/Scripts/MyApp.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

in it I added a "Scripts/MyApp.js" file. So this file added into Script folder with the name of "MyApp.js".


(function () {
    //Create a Module
    var app = angular.module('MyApp', ['ngRoute']);  // Will use ['ng-Route'] when we will implement routing
    //Create a Controller
    app.controller('LoginController', function ($scope) {  // here $scope is used for share data between view and controller
       
    });
})();

Step 7

Now I add a New folder in Script folder with name "AngularController", out put is



Step 8

After Completing step 7 , I add a js file inside "AngularController" with name of "Login.js"



write the code in Login.js


angular.module('MyApp') //extending angular module from First Part
.controller('LoginController', function ($scope, LoginService) { //explained about controller in Login
    //Default Variable
    $scope.submitText = "Login";
    $scope.submitted = false;
    $scope.message = '';
    $scope.isFormValid = false;
    $scope.User = {
        Username: '',
        Password: ''
    };
    //Check form Validation // here f1 is our form name
    $scope.$watch('f1.$valid', function (newValue) {
        $scope.isFormValid = newValue;
    });
    //Save Data
    $scope.SaveData = function (data) {
        if ($scope.submitText == 'Login') {
            $scope.submitted = true;
            $scope.message = '';
            if ($scope.isFormValid) {
                $scope.submitText = 'Please Wait...';
                $scope.User = data;
                LoginService.SaveFormData($scope.User).then(function (d) {
                    if (d == 'Success') {
                        //have to clear form here
                        ClearForm();
                        window.location.href = "/Login/Index"; // page after successful login
                    }
                    if (d == 'Failed!') {
                        $scope.submitText = 'Login';
                        alert('wrong user id or password');
                    }
                });
            }
            else {
                $scope.message = 'Please fill required fields value';
            }
        }
    }
    //Clear Form (reset)
    function ClearForm() {
        $scope.User = {};
        $scope.f1.$setPristine(); //here f1 our form name
        $scope.submitted = false;
    }
})
.factory('LoginService', function ($http, $q) { //explained about factory in Login
    //here $q is a angularjs service with help us to run asynchronous function and return result when processing done
    var fac = {};
    fac.SaveFormData = function (data) {
        var defer = $q.defer();
        $http({
            url: '/Login/Login', //get execute to checking username or password is valid or not.
            method: 'POST',
            data: JSON.stringify(data),
            headers: { 'content-type': 'application/json' }
        }).success(function (d) {
            // Success callback
            defer.resolve(d);
        }).error(function (e) {
            //Failed Callback
            alert('Error!');
            defer.reject(e);
        });
        return defer.promise;
    }
    return fac;
});

Step 9

After writing the "Login.js" , create a contoller in "Controllers" folder at solution explorer. Right click on "Controllers" folder at solution explorer


click on Controller a new window will be open, new rename it to "LoginController" and click on "Add" button.


Step 10

Right click on Index ActionResult  method and click on "Add View.."


After clicking on Add View A new window will be open


now click on "ADD" Button.

After clicking on "Add" button "Index.cshtml"  will be generate. Edit the code of "Index.cshtml"


@{
    ViewBag.Title = "Index";
}
<h2>Sucessd</h2>

Step 11

Now write click on Login ActionResult Add a view and write the code of that view

Login.Cshtnl


@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Login";
}
<style>
     input{
        padding:5px;
        border:1px solid #A5A5A5;
    }
    input.ng-dirty.ng-invalid {
        border:1px solid red;
        background-color:rgb(255, 244, 244);
    }
    .error {
        color:red;
    }
</style>
<h2>Login</h2>
<div ng-controller="LoginController">
    <form novalidate name="f1" ng-submit="SaveData(User)">
        <div style="color:red">{{message}}</div>
        <table>
        <tr>
                <td>Username : </td>
                <td>
                    <input type="text" ng-model="User.Username" name="uUsername" ng-class="submitted?'ng-dirty':''" required />
                    <span class="error" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span>
                </td>
            </tr>
             <tr>
                <td>Password : </td>
                <td>
                    <input type="password" ng-model="User.Password" name="uPassword" ng-class="submitted?'ng-dirty':''" required />
                    <span class="error" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="{{submitText}}" />
                </td>
            </tr>
        </table>
    </form>
</div>
@section scripts{
    <script src="../../Scripts/AngularController/Login.js"></script>
}

Step 12

Add a class in Modles folder withb the name of  "Login.cs"

code of "Login.cs"


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace LoginPageMVCWithAngularJS.Models
{
    public class Login
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        string connString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString; // Read the connection string from the web.config file
        public bool save(Login data)
        {
            bool flag = false;
            SqlConnection con = new SqlConnection(connString);
            con.Open();
            SqlCommand cmd = new SqlCommand("Select count(*) from TblUser where UserName='" + data.UserName + "' and Password='" + data.Password + "'", con);
            flag = Convert.ToBoolean(cmd.ExecuteScalar());
            return flag;
        }
    }
}


Add  Some code in "LoginController.cs"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LoginPageMVCWithAngularJS.Models;
namespace LoginPageMVCWithAngularJS.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
 
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult Login()
        {
            return View();
        }
 
 
        [HttpPost]
        public JsonResult Login(Login u)
        {
            string message = "";
            Login vm = new Login();
            vm.UserName = u.UserName;
            vm.Password = u.Password;
 
            bool i = vm.save(vm);
            if (i)
            { message = "Success"; }
            else
            {
                message = "Failed!";
            }
 
            return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}

Step 13

Now Some changes made in "App_Start" folder files

"BundleConfig.cs"

using System.Web;
using System.Web.Optimization;
namespace LoginPageMVCWithAngularJS
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/angular").Include(
                  "~/Scripts/angular.js",
                  "~/Scripts/angular-route.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
        }
    }
}

Now Edited in "RouteConfig.cs"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LoginPageMVCWithAngularJS
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
            );
        }
    }
}

Now run your application

5 comments: