Populate dropdownlist using AngularJs in asp.net MVC - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

Populate dropdownlist using AngularJs in asp.net MVC

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

Description:
I want to populate the dropdown with city.

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>

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon