Click here to Skip to main content
15,030,954 members
Articles / Web Development / ASP.NET
Posted 25 Mar 2013


47 bookmarked

Connecting to Database Using AngularJS

Rate me:
Please Sign up or sign in to vote.
4.68/5 (24 votes)
25 Mar 2013CPOL3 min read
How to connect to database using AngularJS


AngularJS is built around the belief that declarative programming should be used for building UIs and wiring software components, while imperative programming is excellent for expressing business logic. The framework adapts and extends traditional HTML to better serve dynamic content through two-way data-binding that allows for the automatic synchronization of models and views. As a result, AngularJS deemphasizes DOM manipulation and improves testability.

Design Goals

  • Decouple DOM manipulation from app logic. This improves the testability of the code.
  • Regard app testing as equal in importance to app writing. Testing difficulty is dramatically affected by the way the code is structured.
  • Decouple the client side of an app from the server side. This allows development work to progress in parallel, and allows for reuse of both sides.
  • Guide developers through the entire journey of building an app: from designing the UI, through writing the business logic, to testing.
  • Make common tasks trivial and difficult tasks possible.

Angular follows the MVC pattern of software engineering and encourages loose coupling between presentation, data, and logic components. Using dependency injection, Angular brings traditional server-side services, such as view-dependent controllers, to client-side web applications. Consequently, much of the burden on the backend is reduced, leading to much lighter web applications.

Two-way Data Binding

AngularJS' two-way data binding is its most notable feature and reduces the amount of code written by relieving the server backend from templating responsibilities. Instead, templates are rendered in plain HTML according to data contained in a scope defined in the model. The $scope service in Angular detects changes to the model section and modifies HTML expressions in the view via a controller. Likewise, any alterations to the view are reflected in the model. This circumvents the need to actively manipulate the DOM and encourages bootstrapping and rapid prototyping of web applications.

Some of AngularJS Directives

AngularJS directives allow the developer to specify custom and reusable HTML tags that moderate the behavior of certain elements.

  • ng-app

    Declares an element as a root element of the application allowing behavior to be modified through custom HTML tags.

  • ng-bind

    Automatically changes the text of an HTML element to the value of a given expression.

  • ng-model

    Similar to ng-bind, but allows two-way data binding between the view and the scope.

  • ng-class

    Allows class attributes to be dynamically loaded.

  • ng-controller

    Specifies a JavaScript controller class that evaluates HTML expressions.

  • ng-repeat

    Instantiate an element once per item from a collection.

  • ng-show & ng-hide

    Conditionally show or hide an element, depending on the value of a boolean expression.

  • ng-switch

    Conditionally instantiate one template from a set of choices, depending on the value of a selection expression.

  • ng-view

    The base directive responsible for handling routes that resolve JSON before rendering templates driven by specified controllers.

  • ngClick

    The ngClick allows you to specify custom behavior when element is clicked.

  • ngSubmit

    Enables binding angular expressions to onsubmit events.

  • ngHref

    Using Angular markup like in an href attribute makes the page open to a wrong URL, if the user clicks that link before angular has a chance to replace the with actual URL, the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.


  • Install Visual Studio 2010 or Visual Studio 2012
  • Download AngularJS from here 

Getting Started

To communicate with database using AngularJS, create a Web Service and paste the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Collections;
using System.Web.Script.Serialization;

namespace EmplyeeDetails
    /// <summary>
    /// Summary description for EmpService
    /// </summary>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 

    public class EmpService : System.Web.Services.WebService
        string connection = @"Data Source=RAVINDRA\SQLEXPRESS;
        Initial Catalog=Employee;Integrated Security=SSPI;";

        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string InsertEmployee(string empID, string firstName, 
        	string lastName, string address, string city, 
        	string pincode, string state, string country)
            SqlConnection con = new SqlConnection(connection);
            SqlCommand cmd;
                cmd = con.CreateCommand();
                cmd.CommandText = "INSERT INTO EmployeeDetails
                cmd.Parameters.AddWithValue("@ID", empID);
                cmd.Parameters.AddWithValue("@FirstName", firstName);
                cmd.Parameters.AddWithValue("@LastName", lastName);
                cmd.Parameters.AddWithValue("@Address", address);
                cmd.Parameters.AddWithValue("@City", city);
                cmd.Parameters.AddWithValue("@Pincode", Convert.ToInt32(pincode));
                cmd.Parameters.AddWithValue("@State", state);
                cmd.Parameters.AddWithValue("@Country", country);
                return "Record Inserted Successfully";
            catch (Exception)
                if (con.State == ConnectionState.Open)



Paste this code in a separate .js file:

$ = function () {
            type: "POST",
            url: "EmpService.asmx/InsertEmployee",
            data: "{'empID':'" + $scope.EmpID + "','firstName':'" + 
            $scope.EmpFirstName + "','lastName':'" + $scope.EmpLastName + "',
            'address':'" + $scope.EmpAddress + "','city':'" + $scope.EmpCity + 
            "','pincode':'" + $scope.EmpPincode + "','state':'" + 
            $scope.EmpState + "','country':'" + $ + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
            error: function (msg) {


<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="Employee.aspx.cs" Inherits="EmplyeeDetails.Employee" %>

<!DOCTYPE html>

<html xmlns="" ng-app>
<head runat="server">
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/jquery-1.8.3.min.js"></script>
    <script src="script.js"></script>
    <form id="form1" ng-controller="EmpCtrl" ng-submit="save()">
        <div style="text-align: center;">
            <img alt="" src="banner-careers.jpg" />
        <br />
        <div style="font-family: Verdana; font-size: 12px; margin-left: 450px;">
                    <td style="text-align: right;">Id :
                        <input type="text" id="txtEmpID" ng-model="EmpID" />
                    <td style="text-align: right;">First Name :
                        <input type="text" id="txtEmpFirstName" ng-model="EmpFirstName" />
                    <td style="text-align: right;">Last Name :
                        <input type="text" id="txtEmpLastName" ng-model="EmpLastName" />

                    <td style="text-align: right;">Address :
                        <textarea id="txtEmpAddress" cols="20" rows="2" 
                    <td style="text-align: right;">City :
                        <input type="text" id="txtCity" ng-model="EmpCity" />
                    <td style="text-align: right;">Pin Code :
                        <input type="text" id="txtPinCode" ng-model="EmpPincode" />
                    <td style="text-align: right;">State :

                        <input type="text" id="txtState" ng-model="EmpState" />
                    <td style="text-align: right;">Country :
                        <input type="text" id="txtCountry" ng-model="country" />
                    <td colspan="2" style="text-align: center;">
                        <input type="submit" id="btnSubmit" value="Submit" />

                <input type="button" id="btnFetch" value="Fetch" ng-click="getEmployee()" />

        <hr />

        <table border="1" style="text-align: center; margin-left: 410px;">
                <td>First Name
                <td>Last Name



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


About the Author

Comments and Discussions

QuestionIs it correct for me to add an Entity Data Model in order to connect to an existing database? Pin
Member 1277091531-Oct-16 16:48
MemberMember 1277091531-Oct-16 16:48 
QuestionHow do i put the connection string to be in the web.config page and then use the connectionString name in the EmpService class to connect to the database? Pin
Member 1277091531-Oct-16 16:29
MemberMember 1277091531-Oct-16 16:29 
QuestionAngularJS, RESTful, CRUD application with MSSQL Pin
Member 125136019-May-16 22:29
MemberMember 125136019-May-16 22:29 
GeneralMy vote of 1 Pin
Fawad Raza25-Feb-16 23:42
MemberFawad Raza25-Feb-16 23:42 
QuestionSelection of data Pin
JJBhatt23-Oct-15 21:01
professionalJJBhatt23-Oct-15 21:01 
GeneralMy vote of 1 Pin
barath kumar24-Sep-15 18:25
Memberbarath kumar24-Sep-15 18:25 framework Pin
MUDANZAS VALENCIA mudanzasvalemcia.com18-Aug-15 21:45
MemberMUDANZAS VALENCIA mudanzasvalemcia.com18-Aug-15 21:45 
GeneralAwsome explantion Pin
Member 1137117122-Jun-15 20:13
MemberMember 1137117122-Jun-15 20:13 
GeneralMy vote of 3 Pin
Member 95530434-Feb-15 11:27
MemberMember 95530434-Feb-15 11:27 
QuestionEmpService.asmx.cs does not implement GetEmployeeDetails() Pin
Member 95530434-Feb-15 11:25
MemberMember 95530434-Feb-15 11:25 
General[My vote of 1] Code Pin
Terry Arnett1-Feb-15 15:23
MemberTerry Arnett1-Feb-15 15:23 
Question+1 for resource Pin
Sacha Barber10-Dec-13 12:16
mvaSacha Barber10-Dec-13 12:16 
Questionmissing get employees Pin
Ted Chippington28-Oct-13 4:58
MemberTed Chippington28-Oct-13 4:58 
Questionsecurity Pin
Ted Chippington28-Oct-13 1:34
MemberTed Chippington28-Oct-13 1:34 
AnswerRe: security Pin
Member 766590931-Dec-14 10:04
MemberMember 766590931-Dec-14 10:04 
QuestiongetEmployee()? Pin
jayrobot29-May-13 2:39
professionaljayrobot29-May-13 2:39 
AnswerRe: getEmployee()? Pin
Ravindra T C29-May-13 16:10
professionalRavindra T C29-May-13 16:10 
GeneralRe: getEmployee()? Pin
Member 1127805217-Aug-15 22:33
MemberMember 1127805217-Aug-15 22:33 
GeneralRe: getEmployee()? Pin
aarif moh shaikh31-May-16 2:36
professionalaarif moh shaikh31-May-16 2:36 
AnswerRe: getEmployee()? Pin
walterwz12-Jul-18 11:38
Memberwalterwz12-Jul-18 11:38 
Question$resource Pin
Jeff Wilde26-Mar-13 11:05
MemberJeff Wilde26-Mar-13 11:05 
QuestionNeed few info regarding this js library? Pin
Tridip Bhattacharjee26-Mar-13 8:55
professionalTridip Bhattacharjee26-Mar-13 8:55 
AnswerRe: Need few info regarding this js library? Pin
HariPrasad katakam17-Oct-13 21:32
MemberHariPrasad katakam17-Oct-13 21:32 

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.