Quantcast
Viewing all articles
Browse latest Browse all 9

Getting Started with AngularJS – Create & Read Operations with Database Connectivity

In this article, we are going to see the implementation of Basic Create and Read database operations using AngularJS, ASP.Net WebAPI and Entity Framework.

AngularJS – AngularJS is a popular Open Source JavaScript library from Google,the main aim of Angular is to augment browser based applications with Model-View-Controller(MVC) capability.

Web API - ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building Restful applications on the .NET Framework.

Entity Framework – Entity Framework is an Object Relational Mapper that enables developers to work with Relational data using domain-specific objects.

Let’s get started by creating a simple ASP.Net WebAPI,By taking an Empty template of ASP.Net MVC4 application in the new project window.

Image may be NSFW.
Clik here to view.
image

Create a table with the name person in the database with the following columns.

Image may be NSFW.
Clik here to view.
image

Now,Go to Solution Explorer and Right-click on the Models folder of the Solution and select the Menu option Add,ADO.NET Entity Data Model and give the name as Organization.

Image may be NSFW.
Clik here to view.
image

Select the Generate from database option and Click on Next,Select the database where the table has been created and again Click on Next,Check the tables Checkbox and Click on Finish.

Image may be NSFW.
Clik here to view.
image

The person Model will be added in the Models folder of the solution.

Image may be NSFW.
Clik here to view.
image

Now,Right click on the Controller folder and Add new Controller with the name PersonsController and select Empty API Controller in the template Dropdown.

Open the PersonsController.cs and add following methods for retrieving the people and adding a new person.

PersonsController.cs -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AngWebAPI.Controllers
{
    public class PersonsController : ApiController
    {
        //GET api/person
        //For retrieving all the people
        public IEnumerable<person> GetPeople()
        {
            OrganizationEntities context = new OrganizationEntities();
            var _persons = from p in context.people.AsEnumerable()
                            select p;
            return _persons;
        }

        //POST api/person 
        //For creating new person
        [HttpPost]
        public HttpResponseMessage PostPerson(person p)
        {
            if (p == null)
                return new HttpResponseMessage(HttpStatusCode.BadRequest);
            OrganizationEntities context = new OrganizationEntities();
            context.people.Add(p);
            context.SaveChanges();
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
    }
}

Now Right-click on the Solution,Add an Html file with the name Person.Now Right-click on the Html file and Set As Start Page,add the following Script tag contains the CDN of AngularJS in the head section of the Person.html file.

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

Also, Add the following Script.Which contains the Operations of Retrieving people and Adding a person using AngularJS.

<script type="text/javascript">
        //Defining a Angular module
        var myApp = angular.module('myApp', []);

        //Defining a Angular Controller 
        myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

            //Retrieving the List of people
            GetPersons();
            //Displaying the Save button
            $scope.DisplaySave = true;

            function GetPersons() {
                //Defining the $http service for getting the people
                $http({
                    method: 'GET',
                    url: '/api/persons'
                }).
                success(function (data) {
                    if (data != null || data != 'undefined') {
                       //Assigning people data to the $scope variable
                        $scope.persons = data;
                       //Clearing the Person object in create context and Showing default Gender(Male) Checked
                       $scope.newperson = {
                           Id: '',
                           Gender: 'true'
                       };
                   }
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to retrieve people' + error.message;
                });
            }

            //For creating a new person
            $scope.createPerson = function () {
                //Defining $http service for creating a person
                $http({
                    method: 'POST',
                    url: '/api/persons',
                    data: JSON.stringify($scope.newperson),
                    headers: { 'Content-Type': 'application/JSON' }
                }).
                success(function (data) {
                    //Showing success message
                    $scope.status = "The Person Saved Successfully!!!";
                    //Updating persons Model
                    GetPersons();
                })
                .error(function (error) {
                    //Showing error message
                    $scope.status = 'Unable to create a person: ' + error.message;
                });
            }
       }]);
</script>

And add the following mark-up in the body tag of the Person.html file.

<div data-ng-app="myApp">
    <div data-ng-controller="MyCtrl">
        <form>

            <h2>People Information</h2>
            <table>
                <tr>
                    <td><b>Name</b></td>
                    <td><b>Age</b></td>
                    <td><b>Gender</b></td>
                </tr>
                <tr data-ng-repeat="person in persons">
                    <td>{{person.Name}}</td>
                    <td>{{person.Age}}</td>
                    <td>{{person.Gender && "Male" || "Female" }}</td>
                </tr>
            </table>

            <h2>Save a Person</h2>
            <input type="hidden" data-ng-model="newperson.Id" />
            <b>Name:</b>
            <input type="text" name="Name" id="Name" data-ng-model="newperson.Name" placeholder="Name" required />
            <b>Age:</b>
            <input type="number" name="Age" id="Age" data-ng-model="newperson.Age" placeholder="Age" required />
            <b>Gender:</b>
            <input type="radio" name="gender" data-ng-model="newperson.Gender" value="true" />
            Male
            <input type="radio" name="gender" data-ng-model="newperson.Gender" value="false" />
            Female
            <br />
            <br />
            <input type="button" value="Save" data-ng-show="DisplaySave" data-ng-click="createPerson()" />
            <br />
            <p>{{status}}</p>

        </form>
    </div>
</div>

Now Run the application by pressing Ctrl+F5. And add a Person details.

Image may be NSFW.
Clik here to view.
image

Also,let us verify the database for the inserted records

Image may be NSFW.
Clik here to view.
image

Hope you enjoyed…!!.

In the next article,we are going to see how to Edit and Delete a person using AngularJS.

Happy Coding!!!


Viewing all articles
Browse latest Browse all 9

Trending Articles