Editable Grid AngularJS ASP.NET

How to Create an Editable Grid Using AngularJS & ASP.NET MVC

One of the most important and used feature in web applications is fetching data and displaying data to the end user in a grid or tabular layout. Recently I started learning how to build web applications using AngularJS and ASP.NET C# MVC. In this tutorial, I’ll demonstrate how to create editable grid using AngularJS & ASP.NET MVC.
Source code from this tutorial is available on GitHub.

Also read: How to create a simple Grid Directive Using AngularJS

Getting Started

To create editable grid directive using AngularJS we’ll start by creating a ASP.NET MVC 4 empty project. Right click on the Controllers folder in the project and add a new controller called HomeController. By default there would be an index method inside the HomeController.
Right click on the index method to add a corresponding view.
Here is the default index method:

public ActionResult Index()
{
   return View();
}

Download and include AngularJS and Bootstrap CSS in the index.cshtml view.

<link href="../../style/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="../../script/angular.js" type="text/javascript"></script>

Create an AngularJS app and define a controller function.

var app = angular.module('myApp', []);
app.controller('HomeCtrl', ['$scope', function($scope) {
    $scope.message = "Welcome to Angular .NET MVC 4";
}]);

Add the required ngApp and ngController directive to
the HTML code.

<div ng-app="myApp" ng-controller="HomeCtrl">
    <h2>
        {{message}}
    </h2>
</div>

Try running the app and if all is good, you should be able to view the message defined in scope in the index view.

Creating Data Display in the View

Start by creating an Employee class in your project using which we’ll create a employee list.

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Country { get; set; }
}

Now create a list of dummy employees, so that we have some data to display in our view.

Let’s create a controller method itself which would return the dummy data list as JSONResult.

public JsonResult GetEmployees()
{
    List<Employee> empList = new List<Employee>();

    Employee emp = new Employee { FirstName = "James", LastName = "Bond", Country = "Germany" };
    empList.Add(emp);

    emp = new Employee { FirstName = "Roy", LastName = "Agasthyan", Country = "United States" };
    empList.Add(emp);

    return Json(new { employees = empList });
}

Now the dummy data is ready, all we need is to make a call to the controller method when the loads.
In the index view, inside the HomeCtrl add an AJAX call to the controller method to get the data.

$http({
    method: 'POST',
    url: 'Home/GetEmployees'
})
.then(function (response) {
    $scope.employees = response.data.employees;
}, function (error) {
    console.log(error);
});

The above AJAX call using $http should fetch you the dummy data from the controller method. We have set the data fetched inside $scope.employees.
Now once the data is fetched, we can iterate the employees variable and render the data in tabular form.
Add the following HTML code in which we are using ngRepeat to iterate over the employees object.

<div ng-app="myApp" ng-controller="HomeCtrl" class="container">
    <div class="row">
        <div class="bs-example marginTop50" data-example-id="table-within-panel">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3>Code Handbook</h3></div>
                <div class="panel-body">
                    <p>
                        AngularJS ASP.NET MVC Editable Grid Demo</p>
                </div>
                <table class="table">
                    <thead>
                        <tr>
                            <th>
                                #
                            </th>
                            <th>
                                First Name
                            </th>
                            <th>
                                Last Name
                            </th>
                            <th>
                                Country
                            </th>
                            <th>

                            </th>

                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="emp in employees">
                            <th scope="row">
                                {{$index+1}}
                            </th>
                            <td>
                                {{emp.FirstName}}
                            </td>
                            <td>
                                {{emp.LastName}}
                            </td>
                            <td> {{emp.Country}}
                            </td>
                            <td>
                                <span class="glyphicon glyphicon-pencil"></span>
                            </td>
                        </tr>

                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

Try running yor application and you should be able to view the data in a tabular grid layout.

Create Editable Grid Using AngularJS & ASP.NET MVC
Create Editable Grid Using AngularJS & ASP.NET MVC

Create Editable Grid Using AngularJS

Next we’ll try to make the grid editable. On clicking the edit button we’ll replace the label with input to enable editing. Once finished with editing, click the save button to save the data.
To track each rows edit mode, we need to add a new property to the $scope.employees list. Once the data has been fetched from the controller method,
iterate the object to add a showEdit property to each item.

angular.forEach($scope.employees, function (obj) {
    obj["showEdit"] = true;
})

Here is the complete AngularJS code :

app.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) {

    $http({
        method: 'POST',
        url: 'Home/GetEmployees'
    })
    .then(function (response) {
        console.log(response);
        $scope.employees = response.data.employees;

        angular.forEach($scope.employees, function (obj) {
            obj["showEdit"] = true;
        })

    }, function (error) {
        console.log(error);
    });

} ]);

Once the grid is in edit mode, we’ll need to replace the labels with input text boxes and replace the edit icon with a save icon.
So, modify the tbody section of the table to include the required input boxes and save button.

<tbody>
    <tr ng-repeat="emp in employees">
        <th scope="row">
            {{$index+1}}
        </th>
        <td>
            <span>{{emp.FirstName}}</span>
            <input type="text" ng-model="emp.FirstName" class="form-control">
        </td>
        <td>
            <span>{{emp.LastName}}</span>
            <input type="text" ng-model="emp.LastName" class="form-control">
        </td>
        <td> <span>{{emp.Country}}</span>
            <input type="text" ng-model="emp.Country" class="form-control">
        </td>
        <td>
            <span ng-click="toggleEdit(emp)" class="glyphicon glyphicon-pencil"></span>
            <span ng-click="toggleEdit(emp)" class="glyphicon glyphicon-ok"></span>
        </td>
    </tr>

</tbody>

Save the changes and try running the application. You should have the label, input boxes and both buttons shown in the grid. But we don’t want it that way. It should be in the edit mode only when the edit button is clicked. So, create a function called toggleEdit which would toggle the employee’s showEdit variable.

$scope.toggleEdit = function (emp) {
    emp.showEdit = emp.showEdit ? false : true;
}

Next modify the tbody HTML code to add the ngClick on the both the save and edit icons. Also, add ngShow directive to the input boxes and icons to toggle the display. Here is the modified HTML code :

<tbody>
    <tr ng-repeat="emp in employees">
        <th scope="row">
            {{$index+1}}
        </th>
        <td>
            <span ng-show="emp.showEdit">{{emp.FirstName}}</span>
            <input ng-show="!emp.showEdit" type="text" ng-model="emp.FirstName" class="form-control">
        </td>
        <td>
            <span ng-show="emp.showEdit">{{emp.LastName}}</span>
            <input ng-show="!emp.showEdit" type="text" ng-model="emp.LastName" class="form-control">
        </td>
        <td> <span ng-show="emp.showEdit">{{emp.Country}}</span>
            <input ng-show="!emp.showEdit" type="text" ng-model="emp.Country" class="form-control">
        </td>
        <td>
            <span ng-show="emp.showEdit" ng-click="toggleEdit(emp)" class="glyphicon glyphicon-pencil"></span>
            <span ng-show="!emp.showEdit" ng-click="toggleEdit(emp)" class="glyphicon glyphicon-ok"></span>
        </td>
    </tr>

</tbody>

Save the changes and try running the application and you should be able to see the editable grid in action. On clicking the edit button you would be able to edit the grid values and the $scope.employees object would also get updated on edit save. And we have our editable grid using AngularJS ready.

Create Editable Grid Using AngularJS & ASP.NET MVC
Create Editable Grid Using AngularJS & ASP.NET MVC

Also read : How to create a tool tip directive using AngularJS

Wrapping It Up

In this tutorial, we saw How to Create Editable Grid Using AngularJS & ASP.NET MVC. While editing the data in the grid it automatically updates the $scope variable hence makes it easier to pass the data to database for save operations.
Do let us know any issues, suggestions or corrections in the comments below.