Introduction to AngularJS filters to format and transform and sort


AngularJS is providing set of filters to Format and Transform and Sort the data.

If we want to filter the data inside javascript objects or properties we need to write hundreds of lines of code. In order to archive this we need to spend number of resources and time, But in case of AngularJS it’s completely reverse.

AngularJS is providing in-built filters to format and transform and sort the data.

AngularJS format and transform filters

AngularJS format filters help us to format and transform our data using the following filters.

  1. currency:

    • We can use this currency filter to format currency into specific format

    • for example a decimal property is having just number (300), and now if you want to display that number in currency format like $300.

  2. date:

    • We will use this filter to format date into specific format like “DD/MM/YYYY” or “MM/DD/YYYY” …

  3. filter:

    • We will use this filter to get specific or subset of data from a json object or array

  4. json:

    • This filter allows you to convert a javascript object to JSON string.

    • most of the times we will use this in debugging.

  5. limitTo:

    • we will use this filter to limit a javascript array or string into a specific number of elements.

  6. lowercase:

    • we will use this filter to transform our string to lower case

  7. uppercase:

    • we will use this filter to transform our string to upper case

  8. number:

    • we will use this filter to format a number to string and limit number of decimal

AngularJS sorting filters

we will use sortBy filter to sort the data.

$watch and $watchCollection is not firing/working on data change in angularJS


if $watch and $watchCollection is not firing on data change we need to use 3rd parameter i.e objectEquality parameter (type of boolean)

$watch(watchExpression, listener, [objectEquality])

above statement is the $watch signature with three parameters

in these three parameters third one (objectEquality) is optional and of type boolean

Example 1:

$scope.$watch(‘userProfile.userName’,
function (newValue, oldValue) {
$scope.userName = newValue;
}, true);

Example 2:

$scope.$watch(function () {
return authenticationService.userProfile;
},
function (newValue, oldValue) {
$scope.userProfile = newValue;
}, true);

Happy CodingComputerSmile

invalid uri: the uri string is too long. XDocument load


The reason for the error

invalid uri: the uri string is too long. XDocument load

is the issue with parameter we are passing. It is expecting file path or textreader or xmlreader depends on the method signature we are using.

The parameter we are following should not be the XML data in string.

XDocument.Load method is having 8 overloaded functions as shown below.

//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.IO.TextReader.
public static XDocument Load(TextReader textReader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from an System.Xml.XmlReader.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.Xml.XmlReader.
public static XDocument Load(XmlReader reader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream.
//
// Parameters:
//   stream:
//     The stream that contains the XML data.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader, optionally
//     preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.IO.TextReader.
public static XDocument Load(TextReader textReader, LoadOptions options);
//
// Summary:
//     Loads an System.Xml.Linq.XDocument from an System.Xml.XmlReader, optionally setting
//     the base URI, and retaining line information.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that will be read for the content of the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.Xml.XmlReader.
public static XDocument Load(XmlReader reader, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file, optionally preserving white
//     space, setting the base URI, and retaining line information.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream,
//     optionally preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   stream:
//     The stream containing the XML data.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream, LoadOptions options);

The parameter we are following should not be the XML data in string.

If you want to load xml from string to XDocument use XDocument.Parse as shown in below picture

Screenshot_3

Happy Coding ComputerSmile

How to implement cascading dropdownlist in asp.net mvc using angularJS


 

Here we will learn how to implement cascading dropdown list using angularjs and asp.net mvc.

Should have knowledge on:

You should have knowledge on html , javascript , angularJS and C#.net and asp.net MVC

Preparation:

1. In this article we will use asp.net mvc as service provider and angularJS as client side framework.

2. In asp.net mvc we will build 3 services to get Company Locations, Departments and Managers data.

3. We will use AngularJS $http service to get data from these services.

4. We will use scope object to bind data to UI

Execution:

Open visual Studio and select new project from file menu

and select Asp.Net web application template and enter name then click on OK button.

image

Click on empty tile and select MVC checkbox to create Asp.net MVC empty project then click on OK button

image

Add Content folder and bootstrap.min.css file in it, as shown in below screenshot

Add Scripts folder and angular.min.js file in it, as shown in below screenshot

image

Add app.js file in Scripts folder and write the following code in it.

var MyModule = angular.module('MyModule', []);

 

above code creates angularjs module.

image

Next Create angular Controller for this module as follows

MyModule.controller('myController', ['$scope', '$http', function (scope, http) {
    //Get Locations
    scope.getLocations = function () {
        //Get Locations service call
        http({
            method: 'Get',
            url: '/Home/GetCompanyLocations'
        }).success(function (data, status, headers, config) {
            //assign locations data to scope
            scope.locations = data;
            //setting default value
            if (scope.locations.length > 0) {
                scope.selectedLocation = scope.locations[0];
            }
        }).error(function (data, status, headers, config) {
            alert("Error occured");
        });
    };
    //Get Departments   
    scope.getDepartments = function () {
        if (scope.selectedLocation.Id > 0) {
            scope.departments = null;
            scope.managers = null;
            //Get Departments service call
            http({
                method: 'POST',
                url: '/Home/GetDepartments',
                data: { locationId: scope.selectedLocation.Id }
            }).success(function (data, status, headers, config) {
                //assign departments data to scope
                scope.departments = data;
                //setting default value
                if (scope.departments.length > 0) {
                    scope.selectedDepartment = scope.departments[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.departments = null;
            scope.managers = null;
        }
    };
    //Get Managers
    scope.getManagers = function () {
        if (scope.selectedDepartment.Id > 0) {
            //Get Managers service call
            http({
                method: 'POST',
                url: '/Home/GetManagers',
                data: { deptId: scope.selectedDepartment.Id }
            }).success(function (data, status, headers, config) {
                //assign managers data to scope
                scope.managers = data;
                //setting default value
                if (scope.managers.length > 0) {
                    scope.selectedManager = scope.managers[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.managers = null;
        }
    };
}]);

 

Explanation:

In the above code we have 3 service calls for three dropdowns

1. getLocations

This service get called when the page loads, we can use ngInit directive to call some method on load.

In this service call we will get all the company locations and in success call back, we are assigning the locations to scope.locations object and setting default value for the dropdown using selectedLocation model

2. getDepartments

This service get called when the locations dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the location departments and in success call back, we are assigning the departments to scope.departments object and setting default value for the dropdown using selectedDepartment model

2. getManagers

This service get called when the departments dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the department managers and in success call back, we are assigning the managers to scope.managers object and setting default value for the dropdown using selectedManager model

Add Home controller to controllers folder and one model to models folder and add one action method in home controller and generate a view for it.

image

Write models code in Model (CompanyLocation.cs)

namespace CascadingDropdownList.Models
{
    public class CompanyLocation
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int LocationId { get; set; }
    }
    public class Manager
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int DepartmentId { get; set; }
    }
}

 

Write 3 services 1. GetCompanyLocations 2. GetDepartments 3. GetManagers as follows

        public JsonResult GetCompanyLocations()
        {
            var locations = new List<CompanyLocation>() {
                new CompanyLocation() { Id=0,Name="–select–"},
                new CompanyLocation() { Id=1,Name="Hyderabad"},
                new CompanyLocation() { Id=2,Name="Chennai"},
                new CompanyLocation() { Id=3,Name="Delhi"},
                new CompanyLocation() { Id=4,Name="Bangalore"}
            };
            return Json(locations, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetDepartments(int locationId)
        {
            var departments = new List<Department>() {
                new Department() { Id=1,Name="Accounts",LocationId=1},
                new Department() { Id=2,Name="Software",LocationId=1},
                new Department() { Id=3,Name="CustomerCare",LocationId=1},
                new Department() { Id=4,Name="IT",LocationId=1},
                new Department() { Id=5,Name="Software",LocationId=2},
                new Department() { Id=6,Name="CustomerCare",LocationId=2},
                new Department() { Id=7,Name="IT",LocationId=2},
                new Department() { Id=8,Name="Accounts",LocationId=3},
                new Department() { Id=9,Name="CustomerCare",LocationId=3},
                new Department() { Id=10,Name="IT",LocationId=4}
            };
            var result = departments.Where(d => d.LocationId == locationId).ToList();
            result.Insert(0, new Department() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetManagers(int deptId)
        {
            var locations = new List<Manager>() {
                new Manager() { Id=1,Name="Venki",DepartmentId=1},
                new Manager() { Id=2,Name="Sri",DepartmentId=5},
                new Manager() { Id=3,Name="Balu",DepartmentId=6},
                new Manager() { Id=4,Name="Gopi",DepartmentId=10},
                new Manager() { Id=5,Name="Ramesh",DepartmentId=3},
                new Manager() { Id=6,Name="Ganesh",DepartmentId=2},
                new Manager() { Id=7,Name="Shiva",DepartmentId=7},
                new Manager() { Id=8,Name="Naidu",DepartmentId=2},
                new Manager() { Id=9,Name="ThataRao",DepartmentId=3},
                new Manager() { Id=10,Name="Bala",DepartmentId=4},
                new Manager() { Id=11,Name="Chandu",DepartmentId=8},
                new Manager() { Id=12,Name="Chaitanya",DepartmentId=9}
            };
            var result = locations.Where(d => d.DepartmentId == deptId).ToList();
            result.Insert(0, new Manager() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

 

Then write following code in View(Index.cshtml)

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/app.js"></script>
<div ng-app="MyModule">
    @* using ng-init getLocations() method invoked when the div loads*@
    <div ng-controller="myController" ng-init="getLocations()">
        <div class="row">
            <div class="form-group col-md-offset-2 col-md-2">
                <label for="loc">Select Location:</label>
                <select ng-model="selectedLocation" ng-change="getDepartments()" class="form-control" id="loc"
                        ng-options="location.Name for location in locations track by location.Id"></select>
                <br />
                <label for="dept" ng-show="departments">Select Department:</label>
                <select ng-model="selectedDepartment" ng-change="getManagers()" ng-show="departments" class="form-control" id="dept"
                        ng-options="department.Name for department in departments track by department.Id"></select>
                <br />
                <label for="mng" ng-show="managers">Select Manager:</label>
                <select ng-model="selectedManager" ng-show="managers" class="form-control" id="mng"
                        ng-options="manager.Name for manager in managers track by manager.Id"></select>
                <br />
            </div>
        </div>
    </div>
</div>

Output:

image

image

image

image

Happy Coding ComputerSmile

Screenshot_18

ASP.NET 5 RC1 Web API always returns JSON – Why ?


Code Wala


Hello All,

Note – For this example, I am have used Visual Studio 2015 Update 1 for IDE and ASP.NET 5 RC1.

Recently I started working on an ASP.NET Web API application but I got stuck at one point for few hours. Let’s start from scratch and create the application first then we will see the behavior and various options. As I (most of us) like to start from clean slate so I created an empty ASP.NET application and followed the below stuff

  1. Added Microsoft.AspNet.Mvc as dependency in project.json.
  2. In ConfigureServices method of startup.cs, added services.AddMvc()
  3. In Configure method of startup.cs, added app.UseMvc();
  4. Added a Controllers folder in solution and added a controller class with name as PeopleController which inherits from Controller.
  5. Added the attribute route on the controller as
  6. Now we have done all the necessary set up and added a Controller for Web API. I have added a DataHelper

View original post 287 more words

How to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc


We can get dropdown list selected value or text using ng-model attribute as shown in the below example

How to get dropdown list or select list selected value and selected text in angularJS asp.net mvc

        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "How to get dropdown list or select list selected value and selected text in angularJS :: asp.net mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">

        <select ng-model="selectedColor"
                ng-options="color.Name for color in colors track by color.Id">
        </select>

        <br/>
        Selected Color Name : {{selectedColor.Name}} <br/>
        Selected Color Id : {{selectedColor.Id}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

Output:

Dynamic data binding to dropdown list in angularjs mvc

Happy coding…

Dynamic Data Binding AngularJS SELECT Dropdown list in asp.net MVC


Binding dropdown list or select in web application development is very importent.

we can bind data to dropdown list in angularjs in two ways

1. using ng-options

ng-options is angularJS attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object.

Advantages of ng-options

1. Reducing memory and increasing speed by not creating a new scope for each repeated instance.

2. providing more flexibility in how the <select>‘s model is assigned via the select as part of the comprehension expression

2. using ng-repeat

ng-repeat can be used on <option> element to generate list of options

this is not preferred way of binding dropdown list or select lsit

Example using ng-options
        public JsonResult GetColorsData()
        {
            List<Colors> colors = new List<Colors>()
            {
                new Colors() { Id=1,Name="Red"},
                new Colors() { Id=2,Name="White"},
                new Colors() { Id=3,Name="Blue"},
                new Colors() { Id=4,Name="Green"},
            };
            return Json(colors, JsonRequestBehavior.AllowGet);
        }

@{
    ViewBag.Title = "Dynamic data binding to dropdown list in angularjs mvc";
}

<h3>Colors</h3>
<script src="~/Scripts/angular.min.js"></script>

<div ng-app="ddlExample">
    <div ng-controller="ddlController">
        <select ng-model="selectedColor" ng-options="color.Name for color in colors track by color.Id"></select>
        <br/>
        Selected Color : {{selectedColor.Name}}
    </div>
</div>

<script>
    angular.module('ddlExample', [])
      .controller('ddlController', ['$scope', '$http', function ($scope, $http) {
          $http({
              method: 'Get',
              url: '/Home/GetColorsData'
          }).success(function (data, status, headers, config) {
              //adding colors to model
              $scope.colors = data;
              //set selected color
              $scope.selectedColor = $scope.colors[1];
          }).error(function (data, status, headers, config) {
              $scope.message = 'Error';
          });
      }]);
</script>

 

Output:

Dynamic data binding to dropdown list in angularjs mvc