AngularJs Inline Editing With Web API

19:51

Introduction

In this article I want to show how to create inline editing in angularJs with Wen Api. In my previous article I show how to create web api application.

Inline Editing Image



Table Structure

CREATE TABLE Student(
 [Id] [int] IDENTITY(1,1) primary key NOT NULL,
 [Name] [nvarchar](50) NULL,
 [Address] [nvarchar](500) NULL,
 [Email] [nvarchar](50) NULL,
 [Country] [nvarchar](50) NULL,
 [City] [nvarchar](50) NULL,
 [Mobile] [nvarchar](50) NULL
)

BundleConfig.cs

using System.Web;
using System.Web.Optimization;

namespace AngularJs_Inline_Editing_WebApi
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/css").Include(
                      "~/Content/site.css"));

            bundles.Add(new ScriptBundle("~/js").Include(
                      "~/Scripts/jquery-1.10.2.js",
                      "~/Scripts/angular.js",
                      "~/Scripts/app.js"));
        }
    }
}

app.js

var app = angular.module('myApp', []);//set and get the angular module
app.controller('studentController', ['$scope', '$http', studentController]);

app.directive('ngConfirmClick', [
    function () {
        return {
            priority: 1,
            terminal: true,
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.ngClick;
                element.bind('click', function (event) {
                    if (window.confirm(msg)) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
    }]);

//angularjs controller method
function studentController($scope, $http) {

    //declare variable for mainain ajax load and entry or edit mode
    $scope.loading = true;
    $scope.addMode = false;

    //get all Student information
    $http.get('/api/StudentApi/').success(function (data) {
        $scope.students = data;
        $scope.loading = false;
    })
    .error(function () {
        $scope.error = "An Error has occured while loading posts!";
        $scope.loading = false;
    });

    //by pressing toggleEdit button ng-click in html, this method will be hit
    $scope.toggleEdit = function () {
        this.student.editMode = !this.student.editMode;
    };

    //by pressing toggleAdd button ng-click in html, this method will be hit
    $scope.toggleAdd = function () {
        $scope.addMode = !$scope.addMode;
    };

    //Inser Student
    $scope.add = function () {
        $scope.loading = true;
        $http.post('/api/StudentApi/', this.newstudent).success(function (data) {
            $scope.addMode = false;
            $scope.students.push(data);
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Adding Student! " + data;
            $scope.loading = false;
        });
    };

    //Edit Student
    $scope.save = function () {
        $scope.loading = true;
        var frien = this.student;
        $http.put('/api/StudentApi/' + frien.Id, frien).success(function (data) {
            frien.editMode = false;
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Saving Student! " + data;
            $scope.loading = false;
        });
    };

    //Delete Student
    $scope.deletestudent = function () {
        $scope.loading = true;
        var Id = this.student.Id;
        $http.delete('/api/StudentApi/' + Id).success(function (data) {
            $.each($scope.students, function (i) {
                if ($scope.students[i].Id === Id) {
                    $scope.students.splice(i, 1);
                    return false;
                }
            });
            $scope.loading = false;
        }).error(function (data) {
            $scope.error = "An Error has occured while Saving Student! " + data;
            $scope.loading = false;
        });
    };
}

Site.css

body {
    padding-top: 50px;
    padding-bottom: 20px;
    margin-left: 209px;
    margin-right: -165px;
    background-color: rgb(195, 195, 195);
}
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}
#loader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: grey;
    opacity: .8;
}
.loader {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -32px;
    /* -1 * image width / 2 */
    
    margin-top: -32px;
    /* -1 * image height / 2 */
    
    display: block;
}
table {
    width: 80%;
    border: 1px solid black;
}
table th {
    background-color: #653535;
    color: #fff;
    text-align: center;
    height: 45px;
    font-size: 17px;
}
table tbody tr td {
    width: 200px;
    background-color: #eae0e0;
    height: 40px;
}
table tbody tr td input {
    width: 200px;
    padding: 5px;
    border: 1px solid gray;
    border-radius: 8px;
    height: 30px;
    outline: none;
}
table tbody tr td p {
    text-align: center;
}
.form-group div {
    margin-bottom: 5px;
}
.form-group label {
    float: left;
    padding-right: 10px;
    font-weight: bold;
}
.form-control {
    width: 300px;
    padding: 5px;
    border: 1px solid gray;
    border-radius: 8px;
    outline: none;
}
.btn {
    width: 80px;
    padding: 5px;
    border: 1px solid #000099;
    border-radius: 4px;
    background-color: #3E9EFF;
    color: white;
    font-weight: bold;
    cursor: pointer;
}
.btn:hover {
    background-color: #0000FF;
}

View

@{
    ViewBag.Title = "Home Page";
}


@Scripts.Render("~/js")
@Styles.Render("~/css")

<div ng-app="myApp" ng-controller="studentController" class="container">
    <h1>AngularJs Inline Editing With Web Api</h1>
    <div class="row">
        <div class="col-md-12">
            <strong class="error">{{ error }}</strong>
            <p ng-hide="addMode"><a ng-click="toggleAdd()" href="javascript:;" class="">Add Student</a></p>
            <form name="addStudent" ng-show="addMode" style="width:600px;margin:0px auto;">
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">Name:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" placeholder="Please enter name" ng-model="newstudent.Name" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="address" class="col-sm-2 control-label">Address:</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" id="address" placeholder="Please enter address" ng-model="newstudent.Address" required></textarea>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email:</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" placeholder="Please enter email" ng-model="newstudent.Email" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="country" class="col-sm-2 control-label">Country:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="country" placeholder="Please enter country" ng-model="newstudent.Country" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="city" class="col-sm-2 control-label">City:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="city" placeholder="Please enter city" ng-model="newstudent.City" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="mobile" class="col-sm-2 control-label">Mobile:</label>
                    <div class="col-sm-10">
                        <input type="tel" class="form-control" id="mobile" placeholder="Please enter mobile" ng-model="newstudent.Mobile" required />
                    </div>
                </div>
                <br />
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input type="submit" value="Add" ng-click="add()" ng-disabled="!addStudent.$valid" class="btn" />
                        <input type="button" value="Cancel" ng-click="toggleAdd()" class="btn" />
                    </div>
                </div>
                <br />
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Email</th>
                        <th>Country</th>
                        <th>City</th>
                        <th>Mobile</th>
                        <th>Actions</th>
                    </tr>
                    <tr ng-repeat="student in students">
                        <td>
                            <p ng-hide="student.editMode">{{ student.Name }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.Name" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode">{{ student.Address }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.Address" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode">{{ student.Email }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.Email" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode">{{ student.Country }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.Country" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode">{{ student.City }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.City" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode">{{ student.Mobile }}</p>
                            <input ng-show="student.editMode" type="text" ng-model="student.Mobile" />
                        </td>
                        <td>
                            <p ng-hide="student.editMode"><a ng-click="toggleEdit(student)" href="javascript:;">Edit</a> | <a  ng-confirm-click="Are you sure?" ng-click="deletestudent(student)" href="javascript:;">Delete</a></p>
                            <p ng-show="student.editMode"><a ng-click="save(student)" href="javascript:;">Save</a> | <a ng-click="toggleEdit(student)" href="javascript:;">Cancel</a></p>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div id="loader" ng-show="loading">
        <img src="/images/loader.gif" class="loader" />
    </div>
</div>

Controller

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

namespace AngularJs_Inline_Editing_WebApi.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Api Controller

using AngularJs_Inline_Editing_WebApi.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AngularJs_Inline_Editing_WebApi.Controllers
{
    public class StudentApiController : ApiController
    {
        dbEntities db = new dbEntities();

        //Get All Student
        [HttpGet]
        public IEnumerable Get()
        {
            return db.Students.AsEnumerable();
        }

        //Get Student By Id
        public Student Get(int id)
        {
            Student Student = db.Students.Find(id);
            if (Student == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return Student;
        }

        //Insert Student
        public HttpResponseMessage Post(Student Student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(Student);
                db.SaveChanges();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Student);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Student.Id }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        //Update Student
        public HttpResponseMessage Put(int id, Student Student)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (id != Student.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            db.Entry(Student).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        //Delete Student By Id
        public HttpResponseMessage Delete(int id)
        {
            Student Student = db.Students.Find(id);
            if (Student == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            db.Students.Remove(Student);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK, Student);
        }

        // Memory Management
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Download

You can download this application zip file here

Conclusion

Hi, I hope this will be helpful to you.

You Might Also Like

0 comments