Routing in AngularJs (Part 7)


In this article we will see how to implement the client side routing features in asp.net MVC application using angularJs.

It is one of the cool features of AngularJs Framework.
Now we will see how to implement it by step by step

Step1: Create the blank asp.net MVC 5 application using Visual Studio 2015/2013/2012.

EmptyProject

Step 2: Add the “HomeController“ in Controller folder.

AddController

Step3: Now generate the index view from the Home Controller. Write the code as given below

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
    </div>
</body>
</html>

Step 4: Add the “RoutDemoController “ in RoutDemo folder and keep the following code to generate the partial view

PartialView

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Routing_Demo1.Controllers
{
    public class RoutDemoController : Controller
    {
        // GET: RoutesDemo
        public ActionResult One()
        {
            return PartialView();
        }

        public ActionResult Two()
        {
            return PartialView();
        }

        public ActionResult Three()
        {
            return PartialView();
        }
    }
}

Step 5: Generate the 3 separate partial views like this

<fieldset class="scheduler-border">
    <legend class="scheduler-border">Partial View Page1</legend>
    <p>This is the dummy Text. </p>
    <p>This is the dummy Text. </p><p>This is the dummy Text. </p><p>This is the dummy Text. </p><p>This is the dummy Text. </p>
</fieldset>

Step 6: Now keep the below code in index.cshtml file



<ul>
        <li><a href="/#/RouteOne">Route One</a></li>
        <li><a href="/#/RouteTwo">Route Two</a></li>
        <li><a href="/#/RouteThree">Route Three</a></li>
    </ul>

    <div ng-view></div>

Note:” ng-view” is the angular directive, which is used to render the partial view in given location.
Step 7: Download the angularJs and angular-route.js from Google and kept in Scripts folder.
Step 8: Add you own javascript file in MyScript Folder and write the code like this



var app = angular.module('AngularTest', ['ngRoute']);
var configFunction = function ($routeProvider) {
    $routeProvider
        .when('/RouteOne', {
            templateUrl: 'RoutDemo/One'
        })
        .when('/RouteTwo', {
            templateUrl: 'RoutDemo/Two'
        })
        .when('/RouteThree', {
            templateUrl: 'RoutDemo/Three'
        });
}
configFunction.$inject = ['$routeProvider'];

app.config(configFunction);

Step 9: Call all JavaScript library file in index page and donot forget to include “ng-view” angular directive to render the partial view. The complete code will be as given below.

IndexCodeChange

Step 10: Now run the application, you will see output like given below.

Routing_OP

Summary:
In this post you learn that how to use angularJs routing features in asp.net MVC application.

Consuming Web API Services in AngularJs (Part 6)


Angularjs framework has inbuilt support for consuming external service via $http.get method in json format. There are so many approaches to consume the service.

In this post I will explain one of the most popular approaches to consume external service using Ajax request from WEB API as external Service.

Step 1: Create the blank asp.net MVC 5.0 application.

Step 2: Go to controller folder and right click and add Web API EmpController like given below image

Web API ADD

Step3: Write the code in EmpController like this




using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI_Sample.Models;
using System.Data;
using System.Data.SqlClient;

namespace WebAPI_Sample.Controllers
{
    public class EmpController : ApiController
    { 
      
       [HttpGet]
       public List<Emp> GetEmpDetails()
        {
            List<Emp> Emps = new List<Emp>();
            using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True"))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("Select * from tblEmp", con))
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        Emp objEmp = new Emp();
                        objEmp.Id = Convert.ToInt32(dr["Id"]);
                        objEmp.EmpName = dr["EmpName"].ToString();
                        objEmp.EmpAddress = dr["EmpAddress"].ToString();
                        objEmp.EmpSal = Convert.ToDecimal(dr["EmpSalary"]);
                        Emps.Add(objEmp);
                    }
                    return Emps;
                }
            }
        }

    }
}

Note: Make ensure that there is table I.e tblEmp in your database with Id, EmpName, EmpAddress, EmpSalary field and there should be some dummy data.

Step 4: Now build the application and make ensure that service is working as per as expected. For this you to click F5. Then you will get forbidden error message like this.

Forbidden_Error

Step 5: Now change the URL path like this to execute the Web Api Code

http://localhost:51808/api/Emp/GetEmpDetails

URL Change

Then you will get the data in xml format from Web api service like above image.

Step 6: Write the http get request to consume web api service in angularJs in plain HTML page like given below code




<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../Scripts/angular.min.js"></script>
    <style>
        table, th, td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
        }

            table tr:nth-child(odd) {
                background-color: #f1f1f1;
            }

            table tr:nth-child(even) {
                background-color: #ffffff;
            }
    </style>
    <meta charset="utf-8" />
</head>

<body>
    <fieldset>
        <legend>
            <b> Demo application to consume WEB API in AngualarJs</b>
        </legend>

            <div ng-app="myApp" ng-controller="EmpController">

                <table>
                    <thead>
                        <tr>
                            <th>Emp ID</th>
                            <th>EmpName</th>
                            <th>EmpAddress</th>
                            <th>EmpSal</th>
                        </tr>
                    </thead>
                    <tr ng-repeat="x in EmpNames">
                        <td>{{ x.Id }}</td>
                        <td>{{ x.EmpName }}</td>
                        <td>{{ x.EmpAddress }}</td>
                        <td>{{ x.EmpSal }}</td>
                    </tr>
                </table>

            </div>
       
    </fieldset>
    <script>
        //This is the Module in angular
        var app = angular.module('myApp', []);

        // This is the controller in angular
        app.controller('EmpController', function ($scope, $http) {
            $http.get("http://localhost:51808/api/Emp/GetEmpDetails")
           .success(function (response) {
               $scope.EmpNames = response;
           });

        });
    </script>

</body>

</html>

Step 7: Now run the HTML file and you will get out put like this

FinalOP

Summary:

In this article we learnt that how to create Wep API Service and how to consume it in AngularJs.

How to do basic search functionality in angularJs


Search

We can do basic search functionality in angularJs using filter like given below example. I hope this code we can also use in real time application.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        var app = angular.module("MyApp", []);
        app.controller("MyController", function ($scope) {
            $scope.EmpName = [
                     { Name:'Ram', City:'Bangalore'},
                    { Name:'Mohan', City:'Bangalore'},
                    {Name:'Jon', City:'Bangalore'},
                    {Name:'Rohan', City:'Nepal'}
                                ];
                                });

    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="MyController">
        <p>Enter the Name to be Search <input type="text" name="EmpNameSearch" ng-model="EmpNameSearch" /> </p>
        <table style="border:1px solid" border="1">
            <tr ng-repeat="x in EmpName |filter:EmpNameSearch">
                <td style="width:200px;">{{x.Name}}</td>
                <td style="width:200px;">{{x.City}}</td>
            </tr>
        </table>
    </div>
</body>
</html>

Summary:

We learnt how to use basic search functionality using AngularJs Filter functionality.

Filter in AngularJs (Part 5)


Filter is one of the cool features of angularJs. It is used to indicate by pipeline symbol i.e “|”.
Filter can be added to expression and directive using a pipe character. It is used to format the data as per as our requirement.
There is the following filter example
1. Currency
2. Lowercase
3. Order By
4. Uppercase
5. Number
6. Date
7. Json
8. LimitTo

Now let see each filter example one by one

1. Currency Filter in angularJs :

Currency filter is used to format the currency as given below

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.min.js"></script>
</head>
<body>
    <div ng-app="myApp" ng-controller="myController" >
        Quantity : <input type="number" ng-model="quantity"    />
        Price: <input type="number" ng-model="price" />
        <p>Total: {{quantity*price | currency }} </p>

    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myController', function ($scope) {
            $scope.quantity = 2;
            $scope.price = 200;
        });
    </script>
</body>
</html>

Currency Filter

Other example of Currency Filter with different format



<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        var app = angular.module("MyApp", []);

        app.controller("MyController", function ($scope) {
            $scope.Qnt = 100;
            $scope.Price = 20;
        });
    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="MyController">
      Price:  <input type= "text"  name="Price" value="" ng-model="Price" /> <br /><br />
      Quantity: <input type="text" name="Qnt" value=" " ng-model="Qnt" /><br /> <br />
        Total in US Dollor : {{ Price*Qnt | currency}} <br />
        Totla in RS : {{ Price*Qnt | currency :'Rs.' }} <br />
        No Fraction in RS : {{ Price*Qnt | currency:'Rs.':0}} <br />

    </div>
</body>
</html>

Custom Currency Filter

2. Example of Number Format filter

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
</head>
<body>
    <div ng-app="">
        Enter the input value: <input type="text" name="InputVal" ng-model="InputVal" value=" " /> <br /><br />
        Out Put Value in Number : {{ InputVal | number }} <br />
        Out Put Value in Number 2  : {{ InputVal | number:2 }} <br />
        Out Put Value in Number 4: {{ InputVal | number:4 }} <br />
    </div>
</body>
</html>

Number

3. Example of Lowercase and Uppercase filter



<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        var app = angular.module("MyApp", []);
        app.controller("MyController", function ($scope) {
            $scope.firstName = "Chandradev";
            $scope.LastName = "Prasad";

        });
    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="MyController">
        Complete Name (UpperCase)= {{ firstName +' '+ LastName |uppercase }} <br />
        Complete Name (LowerCase)= {{ firstName +' '+ LastName |lowercase }} <br />
    </div>
</body>
</html>

Case

4. Example of Order by Filter in angularJs

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        angular.module('orderByExample', [])
           .controller('ExampleController', ['$scope', function ($scope) {
               $scope.friends =
                   [{ name: 'Chandradev', phone: '9241503289', age: 25 },
                    { name: 'Aman', phone: '9241503281', age: 26 },
                    { name: 'Karthik', phone: '9241503282', age: 21 },
                    { name: 'Adam', phone: '9241503283', age: 35 },
                    { name: 'Rohit', phone: '9241503284', age: 29 }];
           }]);
    </script>
</head>
<body ng-app="orderByExample">
    <div ng-controller="ExampleController">
        <table class="friend">
            <tr>
                <th>Name</th>
                <th>Phone Number</th>
                <th>Age</th>
            </tr>
            <tr ng-repeat="friend in friends | orderBy:'name'">
                <td>{{friend.name}}</td>
                <td>{{friend.phone}}</td>
                <td>{{friend.age}}</td>
            </tr>
        </table>
    </div>
</body>
</html>

OrderByFilter

5. Example of Date filter in AngularJs

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    
</head>
<body ng-app="">

    <p>
        <label>  Select the date</label>
        <input type="date"  id="date" ng-model="dateValue" />
    </p>
    <p>
        <b> Date Format in Full:</b>  {{dateValue | date :'fullDate'}}
    </p> 
    <p>
        <b> Date Format in Short: </b>  {{dateValue | date :'shortDate'}}
    </p>
    <p>
        <b> Date Format in dd/MM/yyyy:</b> {{dateValue | date :'dd/MM/yyyy'}}
    </p>

</body>
</html>

DateFilter

6. Example of Json filter in AngularJs
Json filter is used to filter data in Json format.

<!DOCTYPE html>	
<html>
<head>
    <title></title>
    <script src="../Scripts/angular.js"></script>
    <script>
           angular.module('radioExample', [])
             .controller('ExampleController', ['$scope', function($scope) {
               $scope.color = {
                 name: 'blue'
               };
               $scope.specialValue = {
                 "id": "12345",
                 "value": "green"
               };
             }]);
    </script>
</head>
<body ng-app="radioExample">
    <form name="myForm" ng-controller="ExampleController">
        <label>
            <input type="radio" ng-model="color.name" value="red">
            Red
        </label><br />
        <label>
            <input type="radio" ng-model="color.name" ng-value="specialValue">
            Green
        </label><br />
        <label>
            <input type="radio" ng-model="color.name" value="blue">
            Blue
        </label><br />
        <tt>color = {{color.name | json}}</tt><br />
    </form>
</body>
</html>
      

Json

7. Example of Limit To Filter:

It is used to filter number only upto specified in given range



<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        angular.module('limitToExample', [])
        //var app = angular.module("limitToExample", [])
           .controller('ExampleController', ['$scope', function($scope) {
             $scope.numbers = [1,2,3,4,5,6,7,8,9];
             $scope.letters = "abcdefghi";
             $scope.longNumber = 2345432342;
             $scope.numLimit = 3;
             $scope.letterLimit = 3;
             $scope.longNumberLimit = 3;
           }]);
    </script>
</head>
<body ng-app="limitToExample">
    <div ng-controller="ExampleController">
        <label>
            Limit {{numbers}} to:
            <input type="number" step="1" ng-model="numLimit">
        </label>
        <p>Output numbers: {{ numbers |limitTo:numLimit }}</p>
        <label>
            Limit {{letters}} to:
            <input type="number" step="1" ng-model="letterLimit">
        </label>
        <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
        <label>
            Limit {{longNumber}} to:
            <input type="number" step="1" ng-model="longNumberLimit">
        </label>
        <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
    </div>
</body>
</html>

LimitTo

Summary:

In this article we learn the basic concept of filter in angularJs.