Sunday, June 5, 2016

How to fill dropdownlist using AngularJs

In this article I am going to explain how to fill dropdownlist using AngularJs in MVC.
How to fill dropdownlist using AngularJs

Description:
I want to populate the dropdown with city name.

Implementation:

To fill the dropdownlist foolow the below given steps:

Model Class (tb_City.cs) :
public partial class Tb_City
    {
        public int Id { get; set; }
        public string CityName { get; set; }
        public Nullable<int> StateId_Fk { get; set; }
    }

Add Controller
Add empty controller to project (AngularController). Write a Json action to fetch the data from database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
namespace MVC_Project.Controllers
{
    public class AngularController : Controller
    {
        //
        // GET: /Angular/
        DemoEntities1 db = new DemoEntities1();
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult Getcity()
        {
            var city = db.Tb_City.ToList();
            return Json(city, JsonRequestBehavior.AllowGet);
           
        }

    }
}

Add View
Now add view for Index action.

Complete View structure (Index.cshtml):
@{
    ViewBag.Title = "MVC-AngualatJs Tutorial";
}
<h2>MVC-AngualatJs Tutorial : Pupulate dropdownlist </h2>
<div ng-app="mvcapp" ng-controller="AngularController">
    <select ng-model="selected" ng-options="x.Id as x.CityName for x in cities | orderBy:'CityName'">
        <option value="">--Select City--</option>
    </select> 
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script>
    var angular = angular.module('mvcapp', []);
    angular.controller('AngularController', function ($scope, CityService) {
        GetAllCity();

        function GetAllCity() {
            var getAllcity = CityService.Getcity();
            getAllcity.then(function (city) {
                $scope.cities = city.data;
            }, function () {
                alert('Records not found');
            });
        }
    })
    angular.service("CityService", function ($http) {
        this.Getcity = function () {
            return $http.get("/Angular/Getcity");
        };
    });
</script>


1 comment:

  1. Hi,
    Really you described it well and good, Thanks for the information, the example you posted here gives a clear idea about the subject.

    Recommended Reading: http://www.credosystemz.com/training-in-chennai/best-angularjs-training-in-chennai/

    ReplyDelete