Sunday 8 October 2017

Implementing server site validation in Angular js

Web Api Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication2.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage="Eid should not be blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage="Name should not be blank.")]
        public string NAME { get; set; }
    }
}

Api Controller

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

namespace WebApplication2.Controllers
{
    [RoutePrefix("api/Empservice")]
    public class EmpserviceController : ApiController
    {
        [HttpGet]
        [Route("Emps")]
        public IHttpActionResult Emps()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
           
        }
        [HttpGet]
        [Route("Emp/{EID:int}", Name="Emp")]
        public IHttpActionResult Emp(int EID)
        {
            try
            {
                using(Database1Entities obj=new Database1Entities())
                {
                    return Ok(obj.EMPs.SingleOrDefault(m => m.EID == EID));
                }
                
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(EMPVM VM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (Database1Entities obj = new Database1Entities())
                    {
                        EMP emp = new EMP();
                        emp.EID = VM.EID??0;
                        emp.NAME = VM.NAME;
                        obj.EMPs.Add(emp);
                        obj.SaveChanges();
                        return Created(new Uri(Url.Link("Emp", new { EID = VM.EID })), "Data Saved.");
                    }
                }
                else
                {
                    return BadRequest(ModelState);
                }
                
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPut]
        [Route("Update/{EID:int}")]
        public IHttpActionResult Update([FromUri]int EID,[FromBody]EMPVM VM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (Database1Entities obj = new Database1Entities())
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        emp.NAME = VM.NAME;
                        obj.SaveChanges();
                        return Ok("Data Updated.");
                    }
                }
                else
                {
                    return BadRequest(ModelState);
                }

            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpDelete]
        [Route("Delete/{EID:int}")]
        public IHttpActionResult Delete(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    EMP emp = obj.EMPs.Find(EID);
                    obj.EMPs.Remove(emp);
                    obj.SaveChanges();
                    return Ok("Data Deleted.");
                }

            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}

Angular js code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="angular.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />
</head>
<body ng-app="app" ng-controller="Ctrl" style="padding-top:5px">
    <div class="container">
        <form class="form-horizontal">
            <div class="form-group">
                <label class="control-label col-lg-4">EID</label>
                <div class="col-lg-4">
                    <input type="text" class="form-control" ng-model="EMP.EID" />
                    <span style="color:red" ng-bind="errEID"></span>
                    
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4">NAME</label>
                <div class="col-lg-4">
                    <input type="text" class="form-control" ng-model="EMP.NAME" />
                    <span style="color:red" ng-bind="errNAME"></span>
                    
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <input type="button" value="Save" style="width:80px" ng-click="save()" class="btn btn-primary" />
                    <input type="button" value="Update" style="width:80px" ng-click="update()" class="btn btn-primary" />
                    <input type="button" value="Reset" style="width:80px" ng-click="reset()" class="btn btn-primary" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-lg-4">SEARCH</label>
                <div class="col-lg-4">
                        <input type="text" ng-model="search.NAME" class="form-control"  placeholder="Search..." />
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-lg-4"></label>
                <div class="col-lg-4">
                    <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                        <thead class="bg-primary">
                            <tr>
                                <th>EID</th>
                                <th>NAME</th>
                                <th>UPDATE</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="c in list|filter:search">
                                <td>{{c.EID}}</td>
                                <td>{{c.NAME}}</td>
                                <td>
                                    <a ng-click="edit(c.EID)">Edit</a>|
                                    <a ng-click="del(c.EID)">Delete</a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        angular.module("app", [])
        .controller("Ctrl", function ($scope, Empfactory) {
            function CLR() {
                $scope.errEID = "";
                $scope.errNAME = "";
                $scope.EMP = new emp();
            } CLR();
            function fill() {
                Empfactory.Gets().then(function (promise) {
                    $scope.list = promise.data;
                });
            } fill();
            $scope.save = function ()
            {
                Empfactory.Post($scope.EMP).error(function (response) {
                    if (response.ModelState["VM.EID"] != "")
                        $scope.errEID = response.ModelState["VM.EID"];
                    else
                        $scope.errEID = "";
                    if (response.ModelState["VM.NAME"] != "")
                        $scope.errNAME = response.ModelState["VM.NAME"];
                    else
                        $scope.errNAME = "";
                }).then(function (promise) {
                    alert(promise.data);
                    fill();
                    CLR();
                });
            }
            $scope.edit = function (EID)
            {
                Empfactory.Get(EID).then(function (promise) {
                    $scope.EMP = promise.data;
                });
            }
            $scope.update = function () {
               
                Empfactory.Put($scope.EMP).error(function (response) {
                    if (response.ModelState["VM.EID"] != "")
                        $scope.errEID = response.ModelState["VM.EID"];
                    else
                        $scope.errEID = "";
                    if (response.ModelState["VM.NAME"] != "")
                        $scope.errNAME = response.ModelState["VM.NAME"];
                    else
                        $scope.errNAME = "";
                }).then(function (promise) {
                    alert(promise.data);
                    fill();
                    CLR();
                });
            }
            $scope.reset = function ()
            {
                CLR();
            }
            $scope.del = function (EID)
            {
                if (confirm('Do you want to delete it ?'))
                {
                    Empfactory.Delete(EID).then(function (promise) {
                        alert(promise.data);
                        fill();
                    });
                }
            }

        })
        .factory("Empfactory", function ($http) {
            var fac = {};
            fac.Gets = function () {
                return $http.get("http://localhost:55683/api/Empservice/Emps");
            }
            fac.Get = function (EID) {
                return $http.get("http://localhost:55683/api/Empservice/Emp/" + EID);
            }
            fac.Post = function (EMP) {
                return $http.post("http://localhost:55683/api/Empservice/Save", EMP);
            }
            fac.Put = function (EMP) {
                
                return $http.put("http://localhost:55683/api/Empservice/Update/" + EMP.EID, EMP);
            }
            fac.Delete = function (EID) {
                return $http.delete("http://localhost:55683/api/Empservice/Delete/" + EID);
            }
            return fac;
        });
        function emp() {
            return {
                EID: null,
                NAME: null
            }
        }
    </script>

</body>
</html>


No comments:

Post a Comment