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

Difference between $scope and $rootScope in angularJS


The main difference is the availability of the property assigned with the object.

$rootScope

  $scope $rootScope
1. It provides local access It provides global access
2. We can have many $scope s We can have only one $rootScope
3. Cannot be used outside the controller Can be used in any controller
4. $scope is created with ng-controller $rootscope is created with ng-app
5. $scope is child object of $rootScope $rootScope is root object

 

Difference between scope and rootscope

$rootScope and $scope Example

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

<div ng-app="MyApp">
    <div class="show-scope-demo">
        <div ng-controller="GreetController">
            Hello {{name}}!
        </div>
        <div ng-controller="ListController">
            <ol>
                <li ng-repeat="name in names">{{name}} from {{department}}</li>
            </ol>
        </div>
    </div>
</div>

<script>
    angular.module('MyApp', [])
  .controller('GreetController', ['$scope', '$rootScope',
    function ($scope, $rootScope) {
        $scope.name = 'World';
        $rootScope.department = 'Angular';
    }
  ])
  .controller('ListController', ['$scope',
    function ($scope) {
        $scope.names = ['venki', 'rohit', 'ganesh'];
    }
  ]);
</script>

Output:

Hello World!

  1. venki from Angular
  2. rohit from Angular
  3. ganesh from Angular

 

Happy coding….

What is $scope in angularjs – MVC


Scope is an object that refers to the application model.

the scope will carry the data between View and controller.

The scope is simple javascript object with properties and methods.

$scope Example

@{
ViewBag.Title = “$scope”;
}
<script src=”~/Scripts/angular.min.js”></script>
<h2>$scope</h2>

<div ng-app=”myApp ng-controller=”myCtrl“>
First Name: <input type=”text” ng-model=”firstName“><br/>
Last Name: <input type=”text” ng-model=”lastName“><br/><br/>
Full Name: {{firstName + + lastName}}
</div>

<script>
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.firstName = “Venki”;
$scope.lastName = “Chikkanti”;
});
</script>

$Scope Explantiaon

MVC architecture using AngularJS

Here controller and view are using $scope to carry the data in-between.

How to consume $scope properties inside view

We can consume $scope properties inside view in two ways

1. using ng-model directive

Ex:

$scope properties :

$scope.firstName = “Venki”;
        $scope.lastName = “Chikkanti”;

using in view :

        First Name: <input type=”text” ng-model=”firstName“><br/>
        Last Name: <input type=”text” ng-model=”lastName“><br/><br/>

2. using angularJS expression

Ex:

$scope properties :

$scope.firstName = “Venki”;
        $scope.lastName = “Chikkanti”;

using in view :

First Name: {{firstName}}
        Last Name: {{lastName}}
        Full Name: {{firstName + + lastName}}

Happy coding….

How to read/import XML file contents to C# object?


Some times we just need to read/import XML file contents to C# object.

So let’s see how to do that.

We already know how to save or export C# object data to XML file

Creating XML file

let’s create xml file with some data as follows

XML file
<?xml version="1.0"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee>
    <Id>1</Id>
    <Name>Venki Chikkanti</Name>
    <Dept>Development</Dept>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>Matt</Name>
    <Dept>Management</Dept>
  </Employee>
  <Employee>
    <Id>3</Id>
    <Name>Mark</Name>
    <Dept>Transport</Dept>
  </Employee>
</ArrayOfEmployee>

Next we have to create C# class as follows

C# object
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Dept { get; set; }
}

Now let’s deserialize XML data and store into C# object and display as follows

Deserializing XML data to C#
static void Main(string[] args)
{
    var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
    List<Employee> emps = new List<Employee>();
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(path);
    string xmlString = xmlDocument.OuterXml;
    using (StringReader read = new StringReader(xmlString))
    {
        Type outType = typeof(List<Employee>);
        XmlSerializer serializer = new XmlSerializer(outType);
        using (XmlReader reader = new XmlTextReader(read))
        {
            emps = (List<Employee>)serializer.Deserialize(reader);
            reader.Close();
        }
        read.Close();
    }
    foreach (var item in emps)
    {
        Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
    }
}

 

Deserialization XML to C#

Total Code:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    public class Class2
    {
        static void Main(string[] args)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
            List<Employee> emps = new List<Employee>();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(path);
            string xmlString = xmlDocument.OuterXml;
            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(List<Employee>);
                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    emps = (List<Employee>)serializer.Deserialize(reader);
                    reader.Close();
                }
                read.Close();
            }
            foreach (var item in emps)
            {
                Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
            }
        }
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Dept { get; set; }
        }
    }
}