Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Connecting to Database Using AngularJS

4.68/5 (24 votes)
25 Mar 2013CPOL3 min read 422.3K   8.4K  
How to connect to database using AngularJS

Introduction

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.

Prerequisites

  • 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:

C#
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 = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]

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

        [WebMethod]
        [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;
            try
            {
                con.Open();
                cmd = con.CreateCommand();
                cmd.CommandText = "INSERT INTO EmployeeDetails
                (ID,FirstName,LastName,Address,City,Pincode,State,Country) 
                VALUES(@ID,@FirstName,@LastName,@Address,@City,@Pincode,@State,@COuntry)";
                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);
                cmd.ExecuteNonQuery();
                return "Record Inserted Successfully";
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

            }
        }
}
}

Script.js

Paste this code in a separate .js file:

JavaScript
$scope.save = function () {
        $.ajax({
            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':'" + $scope.country + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg.d);
            },
            error: function (msg) {
                alert(msg.d);
            }
        });
    };

Employee.aspx

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

<!DOCTYPE html>

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

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

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

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

        </div>
        <hr />

        <table border="1" style="text-align: center; margin-left: 410px;">
            <tr>
                <td>ID
                </td>
                <td>First Name
                </td>
                <td>Last Name
                </td>
                <td>Address
                </td>
                <td>City
                </td>
                <td>Pincode
                </td>
                <td>State
                </td>
                <td>Country
                </td>
            </tr>
            <tr>
                <td>{{ID}}
                </td>
                <td>{{FirstName}}
                </td>
                <td>{{LastName}}
                </td>
                <td>{{Address}}
                </td>
                <td>{{City}}
                </td>
                <td>{{Pincode}}
                </td>
                <td>{{State}}
                </td>
                <td>{{Country}}
                </td>
            </tr>
        </table>
</body>
</html>

Reference

License

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