Click here to Skip to main content
15,881,027 members
Articles / Web Development / ASP.NET
Article

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 419.7K   8.4K   48   23
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)



Comments and Discussions

 
QuestionIs it correct for me to add an ADO.net Entity Data Model in order to connect to an existing database? Pin
Member 1277091531-Oct-16 16:48
Member 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? -VB.net Pin
Member 1277091531-Oct-16 16:29
Member 1277091531-Oct-16 16:29 
QuestionAngularJS, RESTful, CRUD application with MSSQL Pin
Member 125136019-May-16 22:29
Member 125136019-May-16 22:29 
GeneralMy vote of 1 Pin
Fawad Raza25-Feb-16 23:42
Fawad 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
barath kumar24-Sep-15 18:25 
Question.net framework Pin
MUDANZAS VALENCIA mudanzasvalemcia.com18-Aug-15 21:45
MUDANZAS VALENCIA mudanzasvalemcia.com18-Aug-15 21:45 
GeneralAwsome explantion Pin
Member 1137117122-Jun-15 20:13
Member 1137117122-Jun-15 20:13 
GeneralMy vote of 3 Pin
Member 95530434-Feb-15 11:27
Member 95530434-Feb-15 11:27 
QuestionEmpService.asmx.cs does not implement GetEmployeeDetails() Pin
Member 95530434-Feb-15 11:25
Member 95530434-Feb-15 11:25 
General[My vote of 1] Code Pin
Terry Arnett1-Feb-15 15:23
Terry Arnett1-Feb-15 15:23 
Question+1 for resource Pin
Sacha Barber10-Dec-13 12:16
Sacha Barber10-Dec-13 12:16 
Questionmissing get employees Pin
Ted Chippington28-Oct-13 4:58
Ted Chippington28-Oct-13 4:58 
Questionsecurity Pin
Ted Chippington28-Oct-13 1:34
Ted Chippington28-Oct-13 1:34 
AnswerRe: security Pin
Member 766590931-Dec-14 10:04
Member 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
Member 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
walterwz12-Jul-18 11:38 
Question$resource Pin
Jeff Wilde26-Mar-13 11:05
Jeff 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 
HI,

is it a similar kind of library of knockout or the concept is different?

if it is better than knockout then please discuss those best feature here if possible. thanks
tbhattacharjee

AnswerRe: Need few info regarding this js library? Pin
HariPrasad katakam17-Oct-13 21:32
HariPrasad 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.