Click here to Skip to main content
15,890,579 members
Articles / Web Development / HTML
Tip/Trick

Data-binding in AngularJS by consuming ASP.NET Web API Services

Rate me:
Please Sign up or sign in to vote.
4.64/5 (8 votes)
19 Oct 2014CPOL2 min read 54.2K   2K   20   1
Tips to consume Web API services to bind data in AngularJS.

Introduction

Data-binding is the most useful feature in software development technologies. Data-binding in Angular application is the automatic synchronization of data between the model and view components. The model is the single source of truth in our application. The view is a projection of the model. When the model changes, the view reflects the change in application.

Here, we will see how can we consume Web API service for data-binding in AngularJS.

Using the Code

First of all, add an external Angular.min.js file to ASP.NET application. For this, download the JavaScript file from AngularJS official site or download my source code and then fetch it and add Angular.min.js file to your application.

AngularJS

Create an HTML file say AngularForm.html under your application to use AngularJS and link the JavaScript file to the HTML page.

HTML
<head>
    <title>AngularJS Binding App</title>
    <script src="Scripts/angular.min.js"></script> 
</head>

Next, create a controller userController.js to control the application between view and model.

C#
// Creating a module
var userApp = angular.module("userApp", [])

// Creating a controller from the module
userApp.controller("userController", function ($scope) {  
})

Add the JavaScript controller to the HTML page.

HTML
<head>
    <title>AngularJS Binding App</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/userController.js"></script>
</head> 

Add "ng-app" in the HTML tag.

HTML
<html ng-app="userApp" xmlns="http://www.w3.org/1999/xhtml">

Next add HTML tags on the page to create a proper view for the page. Let's create a sample form for user.

HTML
<body>
    <form action="" name="myform">
        <div ng-controller="userController" class="form-horizontal">
            <div class="form-group">
                <label for="message" 
                class="col-md-2 control-label">{{message}}</label>
            </div>
            <div class="form-group">
                <label for="name" 
                class="col-md-1 control-label">Name</label>
                <div class="col-md-2">
                    <input type="text" 
                    ng-model="name" 
                    class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="email" 
                class="col-md-1 control-label">Email</label>
                <div class="col-md-2">
                    <input type="text" 
                    ng-model="email" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="gender" 
                class="col-md-1 control-label">Gender</label>
                <div class="col-md-2">
                    <input type="radio" name="gender" 
                    ng-model="gender" class="radio-inline"/>
                </div>
            </div>
            <div class="form-group">
                <label for="country" 
                class="col-md-1 control-label">Country</label>
                <div class="col-md-2">
                    <select ng-model="country" 
                    class="dropdown form-control" required>
                    <option value="" 
                    selected>-- Choose country --</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="city" class="col-md-1 control-label">City</label>
                <div class="col-md-2">
                    <select ng-model="city" 
                    class="dropdown form-control" required>
                        <option value="" selected>-- Choose city --</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="pincode" 
                class="col-md-1 control-label">PinCode</label>
                <div class="col-md-2">
                    <input type="number" 
                    ng-model="pincode" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="mobileno" 
                class="col-md-1 control-label">MobileNo</label>
                <div class="col-md-2">
                    <input type="number" 
                    ng-model="mobileno" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-1 col-md-10">
                    <input type="submit" 
                    class="btn btn-default" value="Submit"/>
                </div>
            </div>
        </div>
    </form>
</body>

Here in the Div, a directive is used named "ng-controller" that consists of the name of the JavaScript function.The input, select tags used a directive "ng-model" provides the binding between the View and the Model.

Now, we will create models.

Country.cs

C#
namespace SampleAngularJSAppz.Models
{
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

City.cs

C#
namespace SampleAngularJSAppz.Models
{
    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Add Web API Controller Class AngularFormController.cs to the application:

C#
namespace SampleAngularJSAppz.Controllers
{
    public class AngularFormController : ApiController
    {
        // GET api/angularform
        public IEnumerable<String> Get()
        {
            return string[] new { "value1", "value2"};            
        }

        // GET api/angularform/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/angularform
        public void Post([FromBody]string value)
        {
        }

        // PUT api/angularform/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/angularform/5
        public void Delete(int id)
        {
        }
    }
}

Now add code to return data from Web API service to bind view page data through AngularJS controller.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SampleAngularJSAppz.Models;

namespace SampleAngularJSAppz.Controllers
{
    public class AngularFormController : ApiController
    {
        Country[] countries = new Country[] 
        { 
            new Country { Id = 1, Name = "India" }, 
            new Country { Id = 2, Name = "UnitedKingdom" }, 
            new Country { Id = 3, Name = "USA" },
            new Country { Id = 4, Name = "France" },
            new Country { Id = 5, Name = "Scotland"}
        };

        City[] cities = new City[] 
        { 
            new City { Id = 1, Name = "Banglore" }, 
            new City { Id = 2, Name = "Delhi" }, 
            new City { Id = 3, Name = "Bhubaneswar" }, 
            new City { Id = 2, Name = "Mumbai" }, 
            new City { Id = 3, Name = "Hyderabad" }
        };

        // GET api/angularform
        public object Get()
        {
            string[] genders = new string[] { "Male", "Female" };
            object objForm = new { countries, cities, genders };
            return objForm;
        }

        // GET api/angularform/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/angularform
        public void Post([FromBody]string value)
        {
        }

        // PUT api/angularform/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/angularform/5
        public void Delete(int id)
        {
        }
    }
}

In the next step, fetch data from Web API by calling get method from controller.

C#
// Creating a factory from the module
userApp.factory('userFactory', function ($http) {
    return {
        getFormData: function (callback) {
            $http.get('api/AngularForm').success(callback);
        }
    }
})
// Creating a controller from the module
userApp.controller("userController", function ($scope, userFactory) {
    getFormData();
    function getFormData() {
        userFactory.getFormData(function (results) {
            $scope.countries = results.countries;
            $scope.cities = results.cities;
            $scope.genders = results.genders;
        })
    }
    $scope.Save = function () {
        $scope.message = "User Data Submitted"
    }
})

Here, we used userFactory as a function argument is the value returned by the function which is getFormData. Mainly userFactory used to fetch the data from the WebAPI. (The $http service is an inbuilt Angular service that is used for communication with the remote HTTP servers. $scope service acts as a glue between the controller and the view or the HTML template.)

After fetching data from service, then bind data to view (gender, country and city fields).

HTML
<label data-ng-repeat="gender in genders">
       <input type="radio" name="gender" value="{{gender}}" 
       ng-model="gender" class="radio-inline"/> {{gender}}
</label>

<select ng-model="country" class="dropdown form-control" required>
       <option value="" selected>-- Choose country --</option>
       <option ng-repeat="country in countries" 
       value="{{country.Id}}">{{country.Name}}</option>
</select>

<select ng-model="city" class="dropdown form-control" required>
       <option value="" selected>-- Choose city --</option>
        <option ng-repeat="city in cities" 
        value="{{city.Id}}">{{city.Name}}</option>
 </select>

The complete code for AngularForm.html page is as follows:

HTML
<!DOCTYPE html>
<html ng-app="userApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AngularJS Binding App</title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/userController.js"></script>
</head>
<body>
    <form action="" name="myform">
        <div ng-controller="userController" class="form-horizontal">
            <div class="form-group">
                <label for="message" 
                class="col-md-2 control-label">{{message}}</label>
            </div>
            <div class="form-group">
                <label for="name" 
                class="col-md-1 control-label">Name</label>
                <div class="col-md-2">
                    <input type="text" 
                    ng-model="name" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="email" 
                class="col-md-1 control-label">Email</label>
                <div class="col-md-2">
                    <input type="text" 
                    ng-model="email" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="gender" 
                class="col-md-1 control-label">Gender</label>
                <div class="col-md-2">
                    <label data-ng-repeat="gender in genders">
                        <input type="radio" name="gender" 
                        value="{{gender}}" ng-model="gender" 
                        class="radio-inline" ng-true-value="" /> {{gender}}
                    </label>
                </div>
            </div>
            <div class="form-group">
                <label for="country" 
                class="col-md-1 control-label">Country</label>
                <div class="col-md-2">
                    <select ng-model="country" 
                    class="dropdown form-control" required>
                    <option value="" selected>-- Choose country --</option>
                    <option ng-repeat="country in countries" 
                    value="{{country.Id}}">{{country.Name}}</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="city" class="col-md-1 control-label">City</label>
                <div class="col-md-2">
                    <select ng-model="city" 
                    class="dropdown form-control" required>
                        <option value="" selected>-- Choose city --</option>
                        <option ng-repeat="city in cities" 
                        value="{{city.Id}}">{{city.Name}}</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="pincode" 
                class="col-md-1 control-label">PinCode</label>
                <div class="col-md-2">
                    <input type="number" 
                    ng-model="pincode" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <label for="mobileno" 
                class="col-md-1 control-label">MobileNo</label>
                <div class="col-md-2">
                    <input type="number" 
                    ng-model="mobileno" class="form-control" required>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-1 col-md-10">
                    <input type="submit" class="btn btn-default" 
                    value="Submit" ng-click="Save()" />
                </div>
            </div>
        </div>
    </form>
</body>
</html>

This is the final output of AngularForm.html.

SampleForm

Summary

Now, we have learned how we can consume Web API Service for data-binding in AngularJS. Here, I have only written about AngularJS querying values from ASP.NET Web API through HttpGet. You can explore how AngularJS makes other operations on RESTful services.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Mindfire Solutions
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAbout ng-model Pin
Amit Singh Baghel29-Mar-15 4:52
Amit Singh Baghel29-Mar-15 4:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.