Saturday, May 28, 2016

Populate dropdownlist using AngularJs in MVC

In this article I am going to explain how to populate the dropdownlist using AngularJs in MVC
Populate dropdownlist using AngularJs in MVC

I want to populate the dropdown with city.

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>
<script src=""></script>
    var angular = angular.module('mvcapp', []);
    angular.controller('AngularController', function ($scope, CityService) {

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

No comments:

Post a Comment