Jquery And Javascript

Updated : Oct 24, 2019 in Articles

angular js and web API curd operation project

In this article, We will discuss the angular js and web API curd operation project step by step clearly

Step 1: Create a database

Right-click → Databases → click→ New Database→ Write Database Name – ContactsManager→ click OK

Step 2: Create Tables

Table Name – Country

Column Name Data Type Constraint
PKCountryId int PK,not null, Identity
CountryName varchar(50) not null
ZipCodeStart Bigint Allow nulls
ZipCodeEnd Bigint not null
IsActive Bit Allow nulls

Add dummy data into Country Table in Database for testing purpose.

Step 3: Steps to create an MVC project: 

Open Visual Studio→go to File→select  New→click on project→ Expand Visual C# → select web→for visual studio 2013 click on  “ ASP.NET Web Application “ →Fill the Name For ex: ContactsManageUsingAngularJsWebApi → Click OK→ select MVC→ click OK.

Step 4: Steps to create EDMX

Right-click on Project → Add → New Item→ Select Data→ under that select ADO.NET Entity Data Model→ Fill the Name  as ContactsManagerDB → click on ADD → Select Generate from Database → Next→New Connection→ select Microsoft SQL Server → Click Continue →Fill Server Name For ex: vijaykumar – PC→ choose any one Authentication you are working on→ Fill UserName & Password for SQL Authentication→ select Database ContactsManager → Click Ok →check whether Save Entity Connection settings is checked or not→Next→ Check the Tables→ Finish →Now You will get a security warning →click OK → Again to click OK

Step 5: Directory structure of your project.
  • Create Folder in your solution – BO
  • Create New Folder in your solution – CustomScripts.
  • Create sub Folder under CustomScripts – Country.
Step 6: Now adding App.js in your application.

Goto CustomScripts Folder → right click on Folder →Add → New Item → select javaScript File → Name it as App.js

Step 7: Adding MVC  Controller for Country

Go to Solution Explorer →right click on Controllers→ Add→ Controller→click on Empty MVC Controller →Fill the Controller Name as ManageCountryController→ADD

Step 8: Create a view for Index Action method.

Goto Index Actionmethod→right click on Index → select Add View (Make sure that ViewName is the same as ActionMethod Name)→check on Use a Layout or MastePage.

Go to https://angularjs.org/ and download Angular JS 1 which is Uncompressed. Add the angular.js file under Scripts Folder in your solution.

Check whether the references of jquery and bootstrap are existing in _Layout.cshtml or not.

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")

If these references are there, add these references like this.

@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/angular.js"></script>
<script src="~/CustomScripts/App.js"></script>
@Scripts.Render("~/bundles/bootstrap")

If not exist,

       Go to https://jquery.com/download/ and download the Uncompressed, development jquery.

       Go to http://getbootstrap.com/getting-started/ download the bootstrap.

Now add these files under Scripts Folder in your solution.

Add the references from Scripts Folder in _Layout.cshtml.

These script references must and should be there in the _layout page in the same order.

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/CustomScripts/App.js"></script>
<script src="~/Scripts/bootstrap.js"></script>

? Note:  Make sure that App.js reference should be followed by angular.js reference. And also check whether your bootstrap is working or not;

Now Copy and replace the below code in Index.cshtml

@{
    ViewBag.Title = "Index";
}
<h2>Country Form</h2>
<style>
    table tr td a {
        color: blue;
        cursor: pointer;
        text-decoration: underline;
    }
</style>
<button class="btn btn-success" data-toggle="modal" data-target="#countryForm">Add New</button>
<br /><br />
<div ng-app="myapp" ng-controller="countryController" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <table class="table table-striped table-bordered">
        <tr>
            <th>CountryName</th>
            <th>ZipCodeStart</th>
            <th>ZipCodeEnd</th>
            <th>IsActive</th>            
        </tr>
        <tr ng-repeat="country in countries">
            <td>{{country.countryName}}</td>
            <td>{{country.zipCodeStart}}</td>
            <td>{{country.zipCodeEnd}}</td>
            <td>{{country.isActive}}</td>            
            <td><a ng-click="edit(c.pkCountryId)" data-toggle="modal" data-target="#countryForm">Edit</a></td>
            <td><a ng-click="delete(c.pkCountryId)">Delete</a></td>
        </tr>
    </table>

    <div class="modal fade" id="countryForm">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Country Form</h4>
                </div>
                <div class="modal-body">
                    <h2>Create New</h2>
                    <br />
                    <div class="form-group">
                        <label for="countryName">CountryName</label>
                        <input type="text" class="form-control" name="txtCountryName" ng-model="newCountry.countryName" id="countryName" />
                    </div>
                    <div class="form-group">
                        <label for="zipCodeStart">ZipCodeStart</label>
                        <input type="text" class="form-control" name="txtZipCodeStart" ng-model="newCountry.zipCodeStart" id="zipCodeStart" />
                    </div>
                    <div class="form-group">
                        <label for="zipCodeEnd">ZipCodeEnd</label>
                        <input type="text" class="form-control" name="txtZipCodeEnd" ng-model="newCountry.zipCodeEnd" id="zipCodeEnd" />
                    </div>
                    <div class="form-group">
                        <label for="isActive">Is Active</label><br />
                        <input type="checkbox" name="txtIsActive" ng-model="newCountry.isActive" id="isActive" />
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-default" ng-click="insert(newCountry)">Create</button>
                    <button type="submit" class="btn btn-default" ng-click="update(newCountry)">Update</button>
                </div>
            </div>
        </div>
    </div>
</div>
@section scripts{
    <script src="~/CustomScripts/Country/country-service.js"></script>
    <script src="~/CustomScripts/Country/country-controller.js"></script>
}

Step 9: Now goto CustomScritps → App.js File→ Add this code in App.js.

This will Auto-bootstrap your AngularJS Application.

var myapp = angular.module('myapp', []);
Adding AngularJs Controller, Service for Country

Step 10: Now  go to CustomScripts Folder → right-click on Country Folder   → Add→ NewItem→ JavaScript File  Name it as country-service.js

$http is angular JS service which is used here for requesting data from and sending a response to methods of CountryAPIController (post/put/get/delete).

Here is the following code for country-service.js, where countryService is the service Name.

myapp.factory('countryService', function ($http, $q) {
    var factory = {}
    //get all countries
    factory.get = function () {
        var deferred = $q.defer();
        $http.get("/api/ManageCountries")
            .success(deferred.resolve)
            .error(deferred.reject);
        return deferred.promise;
    }
    //insert Country
    factory.insert = function (country) {
        var deferred = $q.defer();        
        $http.post("/api/ManageCountries/" ,country)
         .success(deferred.resolve)
        .error(deferred.reject);
        return deferred.promise;
    }
    //delete Country by id
    factory.delete = function (id) {
        var deferred = $q.defer();
        $http.delete("/api/ManageCountries/" + id)
        .success(deferred.resolve)
        .error(deferred.reject);
        return deferred.promise;
    }
    //edit country by id
    factory.edit = function (id) {
        var deferred = $q.defer();
        $http.get("/api/ManageCountries/" + id)
         .success(deferred.resolve)
         .error(deferred.reject);
        return deferred.promise;
    }
    //update country
    factory.update = function (country) {
        var deferred = $q.defer();        
        $http.put("/api/ManageCountries/", country)
         .success(function (deferred.resolve)
            .error(function ( deferred.reject);
        return deferred.promise;
    }
    return factory;
});

Stpep11: Now adding Angular Js Controller for Country

Goto CustomScriptsCountry→Add JavaScript File under Country Folder and name it as country-controller.js

Here is the following code for country-controller.js, where countryController is the controllerName which was declared in the Index.cshtml by using ng-controller directive.

Now service functions will be called from country-controller.js

myapp.controller('countryController', ['$scope', 'countryService', function ($scope, countryService) {
    //get all countries
    $scope.get = function () {
        countryService.get().then(function (countries) {           
            $scope.countries = countries
        })
    }
    //insert Country
    $scope.insert = function (country) {
        countryService.insert(country).then(function () {
            $scope.get();
        })
    }
    // delete Country by id
    $scope.delete = function (id) {
        countryService.delete(id).then(function () {
            $scope.get();
        })
    }
    // edit country by id
    $scope.edit = function (id) {
        countryService.edit(id).then(function (country) {
            $scope.ctry = country;
        })
    }
    //update Country 
    $scope.update = function (country) {       
        countryService.update(country).then(function () {
            $scope.get();
        })
    }
    $scope.get();
}]);

Step 12: Now Adding BO for Country

Go to Solution Explorer →right-click on BO →Add New Class → CountryBO.cs

Add the following code in CountryBO class

        ContactsManagerEntities db = new ContactsManagerEntities();

        public IEnumerable<Country> GetAllCountries()
        {
            return db.Countries.Select(c => c);
        }
        public Country GetCountryById(int id)
        {
            return db.Countries.Find(id);
        }
        public void Insert(Country country)
        {
            db.Countries.Add(country);
            db.SaveChanges();
        }
        public void Update(Country country)
        {
            db.Entry(country).State = EntityState.Modified;
            db.SaveChanges();
        }
        public void Delete(int id)
        {
            db.Countries.Remove(GetCountryById(id));
            db.SaveChanges();
        }           

Step13: Adding  API  Controller for Country

Go to Solution Explorer→ right-click on ControllersAddController→click on Empty API Controller→Fill the Controller Name as ManageCountryAPIControllerADD.

Copy and replace the below code in ManageCountryAPIController.cs

public class ManageCountriesController : ApiController
    {
        CountryBO objCountryBO = new CountryBO();
        public ManageCountriesController()
        {
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
        }
        // GET: api/ManageCountryAPI
        public IEnumerable Get()
        {
            return objCountryBO.GetAllCountries();
        }
        // GET: api/ManageCountryAPI/5
        public Country Get(int id)
        {
            return objCountryBO.GetCountryById(id);
        }
        // POST: api/ManageCountryAPI
        public void Post([FromBody]Country country)
        {
            if (country != null)
            {
                objCountryBO.Insert(country);
            }
        }
        // PUT: api/ManageCountryAPI/5
        public void Put([FromBody]Country country)
        {
            if (country != null)
            {
                objCountryBO.Update(country);
            }
        }
        // DELETE: api/ManageCountryAPI/5
        public void Delete(int id)
        {
            objCountryBO.Delete(id);
        }
    }

Now run the application by giving Default Controller as ManageCountry and Default ActionMethod as Index in RouteConfig.cs.

After running the application you should get the Countries which are existed in the Database.

angular js and web API project
angular js and web API project

If we click on Add New Button a Bootstrap Modal popup will be displayed with all the fields.

angular js and web API curd operation project

angular js and web API project
angular js and web API project

Now Fill and data and Create a New Country, you can update the country by clicking on Edit link and you can delete

The country by clicking on link Delete.

Leave a Reply

Your email address will not be published. Required fields are marked *