AngularJS is a powerful Javascript framework for dynamic web applications. We often use AngularJS to develop single page application. Here we will explore how to create CRUD (Create Read Update Delete) operation in ASP.NET MVC using Web API and AngularJS.

Let’s start with the database. Create table Person with the following table schema.

Once our database is ready we will create application in Visual Studio 2015. Please follow the steps to create MVC application.

1.Go to File->New->Project and select ASP.NET web application

2.In ASP.NET project window select empty project template, then “under Add folder and code reference for” check the MVC and Web API checkbox.

Now our empty ASP.NET MVC 5 project is created. You can see the folder structure in Solution Explorer window.

3. Let’s install Entity Framework and AngularJS. Go to Tools ->NuGet Package Manager and select Package Manager Console

Model

Now we have to add ADO.NET Entity Data Model. It’s a tool that enables point and click modification in .edmx file. ADO.NET Entity Model designer allows you to visually create and modify entities, mappings and relationship.

We have a database “AdventureWorks” and we have created a table “Person”. By using this tool we are going to create a model in our project.

4.Right click Model folder to add ADO.NET Entity Data Model and name it as “PersonDataContext.edmx”

In choose model contents window select EF Designer from Database. Then configure the connection string as per your database. Once you created entity data model you can see the .edmx file in model folder.

In this demonstration we are going to use Repository pattern. The Repository layer isolates Business layer from Data access layer. In ASP.NET MVC we uses Model layer to interact with Data Access Layer and controller talks to the Controller to perform the Data access operations. In MVC it is good practice to use Repository pattern so if the Model layers need some breaking changes, it’s should have minimum or no impact on Controller layer.

To implement the Repository pattern, create new folder “Interface” in the root directory. Right click Interface folder to add new class “IPersonRepository.cs”. Copy the following code in that file.

 interface IPersonRepository

    {

        IEnumerable<Person> GetAll();

        Person Get(int id);

        Person Add(Person item);

        bool Update(Person item);

        bool Delete(int id);

    }

Create another folder “Repositories” in the root directory. Right click Repositories folder to add new class “PersonRepository.cs”. Here we have to write methods for CRUD operation using Entity Framework.

public class PersonRepository:IPersonRepository

    {

        AdventureWorksEntities DB = new AdventureWorksEntities();

 

        public IEnumerable<Person> GetAll()

        {

            return DB.Person;

        }

 

        public Person Get(int id)

        {

            return DB.Person.Find(id);

        }

 

        public Person Add(Person item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

 

            DB.Person.Add(item);

            DB.SaveChanges();

            return item;

        }

 

        public bool Update(Person item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

            var person = DB.Person.Single(a => a.Id == item.Id);

 

            person.FirstName = item.FirstName;

            person.LastName = item.LastName;

            person.Age = item.Age;

            person.Gender = item.Gender;

            person.City = item.City;

            DB.SaveChanges();

            return true;

        }

        public bool Delete(int id)

        {

            Person item = DB.Person.Find(id);

            DB.Person.Remove(item);

            DB.SaveChanges();

            return true;

        }

    }

Controller

Here we have to create Web API controller. If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

Right Click Controller folder to add WebAPI 2 controller class and name it as “PersonController.cs”.

Copy following code in “PersonController.cs” file.

public class PersonController : ApiController

    {

        static readonly IPersonRepository repository = new PersonRepository();

 

        public IEnumerable GetAllPersons()

        {

            return repository.GetAll();

        }

        public Person AddPerson(Person item)

        {

            return repository.Add(item);

        }

 

        [HttpPut]

        public IEnumerable UpdatePerson(int id, Person item)

        {

            item.Id = id;

            if (repository.Update(item))

                return repository.GetAll();

            else

                return null;

        }

        public bool DeletePerson(int id)

        {

            if (repository.Delete(id))

                return true;

            else

                return false;

        }

    }

Right click Controller folder to create Controller “HomeController.cs” and copy the following code.

    public class HomeController : Controller

    {

        // GET: Home

        public ActionResult Person()

        {

            return View();

        }

    }

AngularJS

First we have to create and configure AngularJS services. Right click “Scripts” folder to add new javascript file “App.js”. Copy the following code.

 

var app = angular.module('adventureModule', []);

app.factory('personService', function ($http) {

    var factory = {};

    factory.getallrecords = function () {

        return $http.get('api/Person/GetAllPersons');

    }

    return factory;

});

Then we have to create AngularJS controller to perform CRUD operation. Right click “Scripts” folder to add new javascript file “Person.cs”  and copy the following code.

/// <reference path="angular.js" />

/// <reference path="App.js" />

 

app.controller('personCtrl', function ($scope, $http, personService) {

 

    $scope.personData = null;

    personService.getallrecords().then(function (d) {

        $scope.personData = d.data;

    }, function (response) {

        alert('error occurred'+response.data.ExceptionMesage);

    });

 

    $scope.Person = {

        Id: '',

        FirstName: '',

        LastName: '',

        Age: '',

        Gender: '',

        City: ''

    };

 

    $scope.clear = function () {

        $scope.Person.Id = '',

        $scope.Person.FirstName = '',

        $scope.Person.LastName = '',

        $scope.Person.Age = '',

        $scope.Person.Gender = '',

        $scope.Person.City = ''

        $scope.addnewdiv = false;

        $scope.updatediv = false;

    };

    //Add new record

 

    $scope.save = function () {

        if ($scope.Person.FirstName != '' && $scope.Person.LastName != '' && $scope.Person.Age != '' && $scope.Person.Gender != '' && $scope.Person.City != '') {

            $http({

                method: 'POST',

                url: 'api/Person/AddPerson',

                data: $scope.Person

 

            }).then(function successCallback(response) {

                $scope.personData.push(response.data);

                $scope.clear();

                alert('Inserted successfully!!');

                $scope.addnewdiv = false;

            }, function errorCallback(response) {

 

                alert('error:' + response.data.ExceptionMesage);

            });

        }

        else {

            alert('Please enter all the values!!');

        }

 

    };

 

    //Edit records

    $scope.edit = function (data) {    

        $scope.Person = { Id: data.Id, FirstName: data.FirstName, LastName: data.LastName, Age: data.Age, Gender: data.Gender, City: data.City }

        $scope.updatediv = true;

    };

 

    //Cancel record

 

    $scope.cancel = function () {

        $scope.clear();

    };

 

    //Update record

    $scope.update = function () {

        if ($scope.Person.FirstName != '' && $scope.Person.LastName != '' && $scope.Person.Age != '' && $scope.Person.Gender != '' && $scope.Person.City != '') {

            $http({

                method: 'PUT',

                url: 'api/Person/UpdatePerson/' + $scope.Person.Id,

                data: $scope.Person

 

            }).then(function successCallback(response) {

                $scope.personData = response.data;

                $scope.clear();

                alert('Updated successfully!!');

                $scope.updatediv = false;

            }, function errorCallback(response) {

 

                alert('error:' + response.data.ExceptionMesage);

            });

        }

        else {

            alert('Please enter all the values!!');

        }

    };

 

    //Delete record

    $scope.delete = function (index) {

        $http({

            method: 'DELETE',

            url: 'api/Person/DeletePerson/' + $scope.personData[index].Id,

 

        }).then(function successCallback(response) {

            $scope.personData.splice(index, 1);

            alert('Record deleted successfully');

        }, function failureCallback(response) {

            alert('error:' + response.data.ExceptionMesage)

        });

 

    };

});

 

View

Double click the HomeController.cs file and Right click on ActionResult Person() to add a view “Person.cshtml” and copy the following HTML code.

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Person</title>

 

    <script src="~/Scripts/angular.js"></script>

    <script src="~/Scripts/App.js"></script>

    <script src="~/Scripts/Person.js"></script>

    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">

</head>

<body ng-app="adventureModule">

    <div ng-controller="personCtrl" class="container-fluid">

        <div><h3>Customer Registration -<span style="color:royalblue"> dotnetfox.com</span> </h3> </div>

        <table ng-cloak class="pure-table">

            <thead>

                <tr>

                    <th hidden="hidden">Id</th>

                    <th>First Name</th>

                    <th>Last Name</th>

                    <th>Age</th>

                    <th>Gender</th>

                    <th>City</th>

                    <th></th>

                </tr>

            </thead>

            <tbody>

                <tr ng-repeat="item in personData">

                    <td style="display:none">{{item.Id}}</td>

                    <td>{{item.FirstName}}</td>

                    <td>{{item.LastName}}</td>

                    <td>{{item.Age}}</td>

                    <td>{{item.Gender}}</td>

                    <td>{{item.City}}</td>

                    <td>

                        <button ng-model="$scope.Person" ng-click="edit(personData[$index])" class="pure-button pure-button-primary">Edit</button>

                        <button ng-click="delete($index)" class="pure-button pure-button-primary">Delete</button>

                    </td>

                </tr>

            </tbody>

        </table>

        <br />

        <div>

            <button ng-click="addnewdiv=true" class="pure-button pure-button-primary">Add Person</button>

        </div>

       

        <div ng-show="addnewdiv" class="pure-form">

            <div>

                <label for="firstname" class="pure-u-1-8">First Name</label>

                <input type="text" data-ng-model="Person.FirstName" />

            </div>

            <div>

                <label for="lastname"  class="pure-u-1-8">Last Name</label>

                <input type="text" data-ng-model="Person.LastName" />

            </div>

            <div>

                <label for="age"  class="pure-u-1-8">Age</label>

                <input type="text" data-ng-model="Person.Age" />

            </div>

            <div>

                <label for="gender"  class="pure-u-1-8">Gender</label>

                <input type="text" data-ng-model="Person.Gender" />

            </div>

            <div>

                <label for="gender"  class="pure-u-1-8">City</label>

                <input type="text" data-ng-model="Person.City" />

            </div>

            <div>

                <button data-ng-click="save()" class="pure-button pure-button-primary">Save</button>

                <button data-ng-click="clear()" class="pure-button pure-button-primary">Cancel</button>

            </div>

        </div>

        <div ng-show="updatediv" class="pure-form">

            <div hidden="hidden">

                <label for="Id" class="pure-u-1-8">Id</label>

                <input type="text" data-ng-model="Person.Id" />

            </div>

            <div>

                <label for="firstname" class="pure-u-1-8">First Name</label>

                <input type="text" data-ng-model="Person.FirstName" />

            </div>

            <div>

                <label for="lastname" class="pure-u-1-8">Last Name</label>

                <input type="text" data-ng-model="Person.LastName" />

            </div>

            <div>

                <label for="age" class="pure-u-1-8">Age</label>

                <input type="text" data-ng-model="Person.Age" />

            </div>

            <div>

                <label for="gender" class="pure-u-1-8">Gender</label>

                <input type="text" data-ng-model="Person.Gender" />

            </div>

            <div>

                <label for="gender" class="pure-u-1-8">City</label>

                <input type="text" data-ng-model="Person.City" />

            </div>

            <div>

                <button data-ng-click="update()" class="pure-button pure-button-primary">Update</button>

                <button data-ng-click="clear()" class="pure-button pure-button-primary">Cancel</button>

            </div>

        </div>

    </div>

</body>

</html>

 

Now we have to change the default Controller and action in Route.Config.cs file.

  public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Home", action = "Person", id = UrlParameter.Optional }

            );

        }

    }                   

Also we have to change the default routeTemplate to add action in WebApiConfig.cs file.

public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            // Web API configuration and services

 

            // Web API routes

            config.MapHttpAttributeRoutes();

 

            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{action}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );

        }

    }

Finally we have done it. Happy coding.!!

 


View demo Download
http://www.dotnetfox.com/Document/1125/demo.PNG

If you enjoyed this article, get email updates (it's free).


Related Articles
  • Creating ASP.NET MVC 4 web application with Empty project templateThis article will show you how to start building ASP.NET MVC 4 web application with Empty project template. Empty project template is basic ASP.NET MVC website generating no code and providing you with nothing to start with. Adding a Model, View & Controller with Empty project template helps you to understand quite clearly than starts with Internet Application template.
  • Introduction to ASP.NET MVCASP.NET MVC provides an alternative approach to traditional ASP.NET web development often referred to as web forms by applying an architectural approach. The MVC or Model-View-Controller pattern splits an application into three separate and distinct layers, the Model layer, the View layer and the Controller layer, each with a very specific set of responsibilities
  • Dynamic Accordion menu or Vertical menu using jQuery in ASP.NET MVCNavigation menu is most important in any web applications. While developing web applications, I used to create stuff more interactive by using jQuery and CSS. It’s quite different to create dynamic navigation menu in ASP.NET MVC. Whether it’s a horizontal or vertical menu, the idea remains same. This article will show you how to create jQuery Accordion menu dynamically in ASP.NET MVC web applicati...
  • Adding a Controller in ASP.NET MVC 4This article will show you how to create a Controller in ASP.NET MVC 4 application. This Controller Layer is the responsible for controlling the application flow and interaction between the Model and the View. Controllers are the brains of an ASP.NET MVC application, requesting data from the Model layer and choosing the correct method of getting that data to the user.
  • Getting started with ASP.NET MVC 5 and AngularJS AngularJS is a powerful javascript framework for dynamic web applications. It is fully extensible for works well with other libraries. The resulting environment is expressive, readable and easy to develop.
  • CRUD operation in ASP.NET MVC using Web API and AngularJS AngularJS is a powerful Javascript framework for dynamic web applications. We often use AngularJS to develop single page application. Here we will explore how to create CRUD (Create Read Update Delete) operation in ASP.NET MVC using Web API and AngularJS.
  • Getting started with ASP.NET MVC 4 I hope you are getting excited to start building ASP.NET MVC 4 application. Visual Studio 2012 IDE is used to build MVC 4 application, also you can install MVC 4 components for Visual Studio 2010. This article will show you that how to start building your first ASP.NET MVC 4 application with internet application template.

Comments
comments powered by Disqus

Thanks for downloading..!!

×
Subscribe via Email
    
message to display in fancybox