👉 Data binding example using AngularJS ng-options with XML data
I’ll first create a simple Web API using Asp.Net and MVC 4, which will provide the data to the HTML SELECT dropdown list. A Web API is a perfect framework for creating web services for high performance Single Page Applications, such as AngularJS. Both the technologies use a similar architecture called MVC for designing powerful web applications.
Let’s get started.
However, before creating the API we will create a small table in SQL Server. The table dbo.Books contains a list of books. We will use the second column in the table, that is, BookName. Please click below link for creating the table.
SQL Server dummy table: dbo.books
The Web API (MVC 4)
Remember: You should have MCV 4 installed on your computer. Therefore, please make sure that you have it.
I am assuming you have some knowledge about creating a Web API in Asp.Net. Don’t worry if you are not well versed with it. I have an article for newbie’s, with an extremely simple and yet useful example.
👉 A Step-by-Step guide to Create your First Web API Service in Asp.Net
Add a Model in the Web API
A Model represents the data in the Web API. Since, in the example here, I have only one Dropdown list on the page, therefore, I’ll add a single property in the Books class, which will return a list of string values (the name of the Books).
Now read: How to Add a Model in Asp.Net Web API project
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BooksApp.Models { public class Books { public string BookName { get; set; } } }
Imports System.Web Namespace BooksApp.Models Public Class Books Public Property BookName() As String Get Return m_BookName End Get Set(value As String) m_BookName = value End Set End Property Private m_BookName As String End Class End Namespace
The Web API Controller
The Controller in this project has a single public method called the Get(), which will handle the http request and return the list of books to the calling application.
Now read: How to Add a Controller Class in Asp.Net Web API
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.http; using System.Web.http; using BooksApp.Models; using System.Data.SqlClient; namespace BooksApp.Controllers { public class BooksController : ApiController { // LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS. List<Books> MyBooks = new List<Books>(); // THE "GET" METHOD WILL RETURN ALL THE BOOKS IN THE TABLE. public IEnumerable<Books> Get() { string sConnString = "Data Source=DNA;Persist Security Info=False;" + "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;"; SqlConnection myConn = new SqlConnection(sConnString); // THE SQL QUERY TO GET THE BOOKS FROM THE TABLE. SqlCommand objComm = new SqlCommand("SELECT *FROM dbo.Books " + "ORDER BY BookName", myConn); myConn.Open(); SqlDataReader reader = objComm.ExecuteReader(); // POPULATE THE LIST WITH DATA. while (reader.Read()) { MyBooks.Add(new Books { BookName = reader["BookName"].ToString() }); } myConn.Close(); return MyBooks; } } }
Option Explicit On Imports System.Net.http Imports System.Web.http Imports System.Data.SqlClient Imports BooksApp.BooksApp.Models Namespace BooksApp Public Class BooksController Inherits ApiController ' LIST OBJECT WILL HOLD AND RETURN A LIST OF BOOKS. Dim MyBooks As New List(Of Books)() ' THE "GET" METHOD WILL RETURN ALL THE BOOKS IN THE TABLE. Public Function [Get]() As IEnumerable(Of Books) Dim sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _ "Initial Catalog=DNA_Classified;User Id=sa;Password=;Connect Timeout=30;" Dim myConn As New SqlConnection(sConnString) ' THE SQL QUERY TO GET THE BOOKS FROM THE TABLE. Dim objComm As New SqlCommand("SELECT BookName FROM dbo.Books " & _ " ORDER BY BookName", myConn) myConn.Open() Dim reader As SqlDataReader = objComm.ExecuteReader() ' POPULATE THE LIST WITH DATA. While reader.Read() MyBooks.Add(New Books() With { _ .BookName = reader("BookName").ToString() _ }) End While myConn.Close() Return MyBooks ' FINALLY, RETURN THE LIST. End Function End Class End Namespace
We need to modify our routing table in the WebApiConfig.cs file (WebApiConfig.vb for Visual Basic). You can find the config file under the App_Start folder in your project. Open the Solution Explorer and expand the App_Start folder. Its here where the Web API determines the actions for each requests it receives. Usually, the Config file will have these parameters.
A Default Route Table
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
Remove “id” Parameter from the Table
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/" );
This is essential since the method that we have declared in the Controller class, does not accept any parameter (to filter the result). Therefore, we don’t need the “id” parameter.
👉 How to use AngularJS ng-options to bind or populate JSON array to a SELECT DropDownList
Over all, I have kept the Web API simple. It could be a little more complicated if you want your API to handle more requests. However, the process remains same.
Finally, I’ll will add an HTML page in my project, where I’ll have an HTML SELECT dropdown list wrapped with AngularJS directives, such as, ng-model and ng-options, along with an AngularJS Expression (in curly braces), representing AngularJS Model and View.
<!DOCTYPE html> <html> <head> <title>Data Binding AngularJS Application using Web API</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myController"> <select ng-model="selected" ng-options="b for b in list"> <option value="">-- Select a Book --</option> </select> <p>Selected Book: <b>{{ selected }}</b></p> </div> </body>
Inside the <script> section, we’ll first initialize the AngularJS app and later declare the controller function, which will make a request to the Web API for data.
<script> var myApp = angular.module('myApp', []); myApp.controller('myController', function ($scope, $http) { var arrBooks = new Array(); $http.get("/api/books/").success(function (data) { $.map(data, function (item) { arrBooks.push(item.BookName); }); $scope.list = arrBooks; }).error(function (status) { alert(status); }); }); </script> </html>