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

Wednesday, December 9, 2015

Cascading DropDownList In MVC

In this article I am going to explain how to create cascading dropdownlist in MVC.

Step1

In Visual Studio Go to  Menu File->New->Project, and click on Project.



Step2


After Clicking on project the given below window will be open (the output looks like):


select ASP.NET MVC 4 Web Appliaction rename the name value to (CascadingDropDownMVC), then click on OK button

Step3

After completing the step 2 new window will be open the output is looks like


In it select the Basic  project template and click on "OK" button, after clicking on "OK" button your solution explorer look like



Step 4

After the completing step 3 , I add a class in my model (Right click on Model folder at solution explorer) the output will look like(Here click on class menu item)



Now new window will be open,  rename the class name (StateCity.cs)  (output look like) then click on Add Button.


your "StateCity.cs" class has been created.

Step 5

Before writing the code in class firstly create  two tables "city" and "state" in your database ,
you may use the given below script for tables creation.

DataBase Structure of City,State


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[State](
                [StateID] [int] IDENTITY(1,1) NOT NULL,
                [StateName] [varchar](50) NOT NULL,
                [active] [bit] NULL,
                [Latitude] [varchar](35) NULL,
                [Longitude] [varchar](35) NULL,
 CONSTRAINT [PK_StateMaster] PRIMARY KEY CLUSTERED
(
                [StateID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[State] ON
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (3, N'Andaman and Nicobar', 1, N'6deg.  and 14deg.N', N'92deg. and 94deg. E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (4, N'Andhra Pradesh', 1, N'12deg.41min and 22Deg. N', N'77deg.and 84deg.40min E')
INSERT [dbo].[State] ([StateID], [StateName], [active], [Latitude], [Longitude]) VALUES (5, N'Assam', 1, N'24deg.  3min and 27deg. 58min N', N'89deg.5min and 96deg. 1min E')
SET IDENTITY_INSERT [dbo].[State] OFF
/****** Object:  Table [dbo].[TCity]    Script Date: 12/10/2015 12:34:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TCity](
                [CityID] [int] IDENTITY(1,1) NOT NULL,
                [CityName] [varchar](100) NOT NULL,
                [StateId] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
                [CityID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[TCity] ON
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (2, N'ANDAMAN ISLAND', 3)
INSERT [dbo].[TCity] ([CityID], [CityName], [StateId]) VALUES (3, N'NICOBAR ISLAND', 3)
SET IDENTITY_INSERT [dbo].[TCity] OFF
/****** Object:  ForeignKey [fk_StateId]    Script Date: 12/10/2015 12:34:50 ******/
ALTER TABLE [dbo].[TCity]  WITH CHECK ADD  CONSTRAINT [fk_StateId] FOREIGN KEY([StateId])
REFERENCES [dbo].[State] ([StateID])
GO
ALTER TABLE [dbo].[TCity] CHECK CONSTRAINT [fk_StateId]


Now we write the code of  "StateCity.cs" class.

StateCity.cs


using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace CascadingDropDownMVC.Models
{
    public class StateCity
    {

      //return connection string

        string Constr = ConfigurationManager.ConnectionStrings["Con"].ToString();
     
        public List<SelectListItem> State = null;
        public int StateID { set; get; }
        public List<SelectListItem> City = null;
        public int CityID { set; get; }

        //return state list
        public List<SelectListItem> GetState()
        {
            SqlDataReader dr = null;
            State = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select StateID,StateName from State", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
           
            State.Add(new SelectListItem { Text = "Select State", Value = "0", Selected = true });
            while (dr.Read())
            {
                State.Add(new SelectListItem { Text = Convert.ToString(dr["StateName"]), Value = Convert.ToString(dr["StateID"]), Selected = true });
            }
            return State;
        }
        //return city list on behalf of state id

        public List<SelectListItem> GetCity(string StateID)
        {
            SqlDataReader dr = null;
            City = new List<SelectListItem>();
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("select CityID,CityName from TCity  where StateId=" + StateID + "", con);
            cmd.CommandType = CommandType.Text;
            dr = cmd.ExecuteReader();
            City.Add(new SelectListItem { Text = "Select City", Value = "0", Selected = true });
            while (dr.Read())
            {
                City.Add(new SelectListItem { Text = Convert.ToString(dr["CityName"]), Value = Convert.ToString(dr["CityID"]), Selected = true });
            }
            return City;
        }
    }
}

Step 6
Now Right Click on Controller folder at solution explorer add a new Controller (the out put will look like) now click on Controller


 a new window will be open name it to  index. The out put will look like


now click on Add button
Step 8
Write the code in IndexController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadingDropDownMVC.Models;
namespace CascadingDropDownMVC.Controllers
{
    public class IndexController : Controller
    {
        //
        // GET: /Index/
        public ActionResult Index()
        {
            StateCity obj = new StateCity();
            ViewBag.State = obj.GetState();
            return View();
        }
        public JsonResult City(string StateID)
        {
            List<SelectListItem> City = new List<SelectListItem>();
            StateCity obj = new StateCity();
            City = obj.GetCity(StateID);
            return Json(City);
        }
    }
}

Step 9

Create a View for this contoller, now right click on Index ActionResult method , a popup window will be open click on Add View  and write the code given below:

@model CascadingDropDownMVC.Models.StateCity
@{
    ViewBag.Title = "Cascading DropdownList in MVC";
}
<style type="text/css">
  .inpt       { border:1px solid #CCC; background:#ffffff; margin:0 0 5px; padding:5px; color:#444444; }
.inpt:hover { -webkit-transition:border-color 0.3s ease-in-out; -moz-transition:border-color 0.3s ease-in-out; transition:border-color 0.3s ease-in-out; border:1px solid #AAA; }
.inpt:focus { border:1px solid #395b77; outline:none; }
</style>
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
    $(document).ready(function () {
        $("#StateID").change(function () {
            if ($("#StateID").val() != "0") {
                var options = {};
                options.url = "/index/City";
                options.type = "POST";
                options.data = JSON.stringify({ StateID: $("#StateID").val() });
                options.dataType = "json";
                options.contentType = "application/json";
                options.success = function (City) {
                    $("#city").empty();
                    for (var i = 0; i < City.length; i++) {
                        alert(City[i].Value);
                        alert(City[i].Text);
                        $("#city").append('<option value="' + City[i].Value + '">' + City[i].Text + '</option>');
                    }
                    $("#city").prop("disabled", false);
                };
                options.error = function () { alert("Error retrieving city!"); };
                $.ajax(options);
            }
            else {
                $("#city").empty();
                $("#city").prop("disabled", true);
            }
        });
    });
</script>
<h2>Cascading DropdownList in MVC</h2>
<table>
<tr>
<td style="width:50px;"><b>State</b> :</td>
<td>@Html.DropDownListFor(model => model.StateID, new SelectList(ViewBag.State, "Value", "Text"), new { @class = "inpt" })</td>
</tr>
<tr>
<td style="width:50px;"><b>City</b> :</td>
<td>@Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "inpt" })</td>
</tr>
</table>

Now rest of changes we will done in "RouteConfig.cs", At the solution explorer App_Start folder conatin this file

changes in RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CascadingDropDownMVC
{
    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 = "Index", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Now Run you application output will look like:

Output: