Monday, 1 January 2018

Example of ng-gride in angular js

  1. <!DOCTYPE html>  
  2. <html ng-app="myApp">  
  3. <head>  
  4.     <title>NG Grid Demo</title>  
  5.     <>  
  6.         .gridStyle  
  7.         {  
  8.             border: 5px solid #d4d4d4;  
  9.             width: 400px;  
  10.             height: 200px;  
  11.         }  
  12.     </style>  
  13.     <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />  
  14.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>  
  15.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>  
  16.     <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>  
  17.     <script type="text/javascript">  
  18.         var app = angular.module('myApp', ['ngGrid']);  
  19.         app.controller('MyCtrl'function ($scope) {  
  20.             $scope.Data = [{ Name: "Sachin", Skill: "ASP.NET" ,location:"Delhi"},  
  21.                              { Name: "Ramesh", Skill: "C#.NET, VB", location: "Chenai" },  
  22.                             { Name: "Pradeep", Skill: "ASP.NET MVC", location: "Bangalore" },  
  23.                              { Name: "Manas", Skill: "SQL Server", location: "Chenai" },  
  24.                            { Name: "Sachin", Skill: "ASP.NET", location: "Bangalore" }, ];  
  25.             $scope.gridOptions = { data: 'Data' };  
  26.         });  
  27.     </script>  
  28. </head>  
  29. <body ng-controller="MyCtrl">  
  30.     <div>  
  31.         <labl><b> Sample Demo to NG Grid</b></labl>  
  32.     </div>  
  33.     <div class="gridStyle" ng-grid="gridOptions"></div>  
  34. </body>  
  35. </html>  
Output
 
There are four steps to show a sample grid, if we observe the preceding code.
Passed "ngGrid" as dependency to the module
  1. var app = angular.module('myApp', ['ngGrid']);
Assign some data to scope
  1. [{Name: "Sachin", Skill: "ASP.NET" ,location:"Delhi"},];
Set the data of the scope to gridOptions as 
  1. $scope.gridOptions = {data: ‘Data’};
It is like assigning a datasource to nggrid, similar to Gridview1.datasource=dataset in ASP.NET.
Bind the data to the page 
  1. <div class="gridStyle" ng-grid="gridOptions"></div>
It is like binding data to a GridView, similar to Gridview1.dataBind() in ASP.NET.
Don't forget to add the scripts and styles needed for ng-grid in the head section of the code.
Let us create a DB and Bind data to ng-grid by web API calls.
Example-2
Step 1
Let us create an Employee Table.
 
Step 2
We will create a web API that will return the employee data.
  1. public class EmployeeAPIController : ApiController  
  2.     {  
  3.         private EmployeeEntities db = new EmployeeEntities();  
  4.          
  5.         public IEnumerable<Employee> GetEmployees()  
  6.         {  
  7.             return db.Employees.AsEnumerable();  
  8.         }  
  9.     }  
Step 3
Add module service controller and html code.
Module
  1. var app;  
  2. (function () {  
  3.     app = angular.module("EmployeeModule", ['ngGrid']);  
  4. })();  
Service
  1. app.service('EmployeeService'function ($http) {  
  2.   
  3.     this.getAllEmployee = function () {  
  4.         return $http.get("/api/EmployeeAPI");  
  5.     }  
  6. });  
Controller
  1. app.controller('EmployeeController'function ($scope, EmployeeService) {  
  2.     
  3.     GetAllRecords();  
  4.     function GetAllRecords() {  
  5.         var promiseGet = EmployeeService.getAllEmployee();  
  6.         promiseGet.then(function (pl) { $scope.Employees = pl.data, $scope.Data=pl.data },  
  7.               function (errorPl) {  
  8.                   $log.error('Some Error in Getting Records.', errorPl);  
  9.               });  
  10.     }  
  11.     $scope.gridOptions = { data: 'Data' };  
  12. });  
Index.html
  1. <html data-ng-app="EmployeeModule">  
  2. <head>  
  3.     <style type="text/css">  
  4.         .gridStyle  
  5.         {  
  6.             border: 5px solid #d4d4d4;  
  7.             width: 1000px;  
  8.             height: 200px;  
  9.         }  
  10.     </style>  
  11. </head>  
  12. <body data-ng-controller="EmployeeController">  
  13.   
  14.     <div class="gridStyle" ng-grid="gridOptions"></div>  
  15. </body>  
  16. </html>  
  17. <script src="~/Scripts/angular.js"></script>  
  18. <script src="~/Scripts/EmployeeScripts/Module.js"></script>  
  19. <script src="~/Scripts/EmployeeScripts/Service.js"></script>  
  20. <script src="~/Scripts/EmployeeScripts/Controller.js"></script>  
  21. <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />  
  22. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>  
  23. <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>  
Output

Now, we have seen data from the database and binding to an ng-grid. Let us see now what the features are in ng-grid to make it more useful. We will do a sample ng-grid binding, editing, paging, sorting and grouping the records.
Example-3
  1. <!DOCTYPE html>  
  2. <html ng-app="myApp">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>Working With NG-Grid </title>  
  7.   
  8.     <style type="text/css">  
  9.         .gridStyle  
  10.         {  
  11.             border: 1px solid rgb(212, 212, 212);  
  12.             width: 800px;  
  13.             height: 370px;  
  14.             margin-left: 50px;  
  15.             color: coral;  
  16.         }  
  17.         .red {  
  18.     background-color: green;  
  19.     color: red;  
  20. }  
  21.     </style>  
  22.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>  
  23.     <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />  
  24.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>  
  25.     <script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>  
  26.     <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>  
  27.     <script>  
  28.         var app = angular.module('myApp', ['ngGrid']);  
  29.         app.controller(  
  30.                         'MyCtrl',  
  31.                         function ($scope) {  
  32.                             var Company;  
  33.                             var Model;  
  34.                             var Price;  
  35.                             var Stocks;  
  36.                             var x;  
  37.                             $scope.submit = function () {  
  38.                                 Company = $scope.Company;  
  39.                                 Model = $scope.Model;  
  40.                                 Price = $scope.Price;  
  41.                                 Stocks = $scope.Stocks;  
  42.                                 $scope.myData.push({  
  43.                                     Company: Company,  
  44.                                     Model: Model,  
  45.                                     Price: Price,  
  46.                                     Stocks: Stocks  
  47.                                 });  
  48.                             };  
  49.   
  50.                             $scope.myData = [{ "Company": "Samsung", "Model": "Samsung Galaxy Grand 2", "Price": 5000, "Stocks": 4 },  
  51.                                              { "Company": "Samsung", "Model": "Samsung Galaxy S3 Neo", "Price": 9000, "Stocks": 41 },  
  52.                                            { "Company": "Samsung", "Model": "Samsung Galaxy Grand Max", "Price": 11000, "Stocks": 4 },  
  53.                                             { "Company": "MicroMax", "Model": "Micromax Canvas Blaze", "Price": 6300, "Stocks": 0 },  
  54.                                            { "Company": "MicroMax", "Model": "Micromax Canvas Duddle", "Price": 11000, "Stocks": 3 },  
  55.                                              { "Company": "MicroMax", "Model": "Micromax Canvas Duddle- SPL", "Price": 11000, "Stocks": 3 },  
  56.                                              { "Company": "Blackberry", "Model": "Blackberry Z30", "Price": 19000, "Stocks": 10 },  
  57.                                            { "Company": "Blackberry", "Model": "Micromax bold  9780", "Price": 12900, "Stocks": 20 },  
  58.   
  59.                             ],  
  60.   
  61.   
  62.                             $scope.gridOptions = {  
  63.   
  64.                                 data: 'myData',  
  65.                                 pagingOptions: $scope.pagingOptions,  
  66.                                 enablePinning: true,  
  67.                                 enablePaging: true,  
  68.                                 showFooter: true,  
  69.                                 enableColumnResize: true,  
  70.                                 enableCellSelection: true,  
  71.                                 columnDefs: [  
  72.                                         {  
  73.                                             field: "Company",  
  74.                                             width: 180,  
  75.                                             pinned: true,  
  76.                                             enableCellEdit: true  
  77.                                         },  
  78.                                         {  
  79.                                             field: "Model",  
  80.                                             width: 200,  
  81.                                             enableCellEdit: true  
  82.                                         },  
  83.                                         {  
  84.                                             field: "Price",  
  85.                                             width: 100,  
  86.                                             enableCellEdit: true  
  87.                                         },  
  88.                                         {  
  89.                                             field: "Stocks",  
  90.                                             width: 120,  
  91.                                             enableCellEdit: true,  
  92.                                             cellTemplate: basicCellTemplate  
  93.                                         },  
  94.                                         {  
  95.                                             field: "Action",  
  96.                                             width: 200,  
  97.                                             enableCellEdit: false,  
  98.                                             cellTemplate: '<button id="editBtn" type="button" class="btn btn-xs btn-info"  ng-click="updateCell()" >Click a Cell for Edit </button>'  
  99.                                         }]  
  100.   
  101.                             };  
  102.   
  103.                             $scope.selectedCell;  
  104.                             $scope.selectedRow;  
  105.                             $scope.selectedColumn;  
  106.   
  107.                             $scope.editCell = function (row, cell, column) {  
  108.                                 $scope.selectedCell = cell;  
  109.                                 $scope.selectedRow = row;  
  110.                                 $scope.selectedColumn = column;  
  111.                             };  
  112.   
  113.                             $scope.updateCell = function () {  
  114.   
  115.                                 //   alert("checking");  
  116.                                 $scope.selectedRow[$scope.selectedColumn] = $scope.selectedCell;  
  117.                             };  
  118.   
  119.                             var basicCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()" ng-click="editCell(row.entity, row.getProperty(col.field), col.field)"><span class="ui-disableSelection hover">{{row.getProperty(col.field)}}</span></div>';  
  120.   
  121.                             $scope.filterOptions = {  
  122.                                 filterText: "",  
  123.                                 useExternalFilter: true  
  124.                             };  
  125.   
  126.                             $scope.gridOptions.sortInfo = {  
  127.                                 fields: ['Company', 'Price'],  
  128.                                 directions: ['asc'],  
  129.                                 columns: [0, 1]  
  130.                             };  
  131.   
  132.                             $scope.totalServerItems = 0;  
  133.   
  134.                             $scope.pagingOptions = {  
  135.                                 pageSizes: [5, 10, 20],  
  136.                                 pageSize: 5,  
  137.                                 currentPage: 1  
  138.                             };  
  139.   
  140.                             $scope.changeGroupBy = function (group1, group2) {  
  141.                                 $scope.gridOptions.$gridScope.configGroups = [];  
  142.                                 $scope.gridOptions.$gridScope.configGroups.push(group1);  
  143.                                 $scope.gridOptions.$gridScope.configGroups.push(group2);  
  144.                                 $scope.gridOptions.groupBy();  
  145.                             }  
  146.                             $scope.clearGroupBy = function () {  
  147.                                 $scope.gridOptions.$gridScope.configGroups = [];  
  148.                                 $scope.gridOptions.groupBy();  
  149.                             }  
  150.   
  151.                         });  
  152.     </script>  
  153. </head>  
  154. <body ng-controller="MyCtrl">  
  155.     <div class="panel panel-danger">  
  156.         <div class="panel-heading"></div>  
  157.         <div class="panel-body">  
  158.             <form class="input" ng-submit="submit()" role="form">  
  159.                 <div style="border: 2px solid gray;width:600px;" >  
  160.                     <labl> <b> Add a New Model:  NG GRID DEMO </b></labl>  
  161.                     <div class="form-group">  
  162.                         <label"><b>Company:</b></label>   
  163.                 <input id="inputs" class="form-control" type="text" ng-model="Company">  
  164.                     </div>  
  165.                     <div class="form-group">  
  166.                         <label><b>Model :</b></label>  
  167.                         <input id="Number1" class="form-control" type="text" ng-model="Model">  
  168.                     </div>  
  169.                     <div class="form-group">  
  170.                         <label>Price</label>  
  171.                         <input id="Date1" class="form-control" type="number" ng-model="Price">  
  172.                     </div>  
  173.                     <div class="form-group">  
  174.                         <label>Stocks</label>  
  175.                         <input id="Number2" class="form-control" type="number" ng-model="Stocks">  
  176.                     </div>  
  177.   
  178.                     <div class="form-group">  
  179.                         <input  
  180.                             type="submit" value="submit" id="but" class="btn btn-success">  
  181.                         <button type="button" ng-click="changeGroupBy('Company','Price')">Company By Name and Price</button>  
  182.                         <button type="button" ng-click="clearGroupBy()">Clear Group</button>  
  183.                     </div>  
  184.                 </div>  
  185.             </form>  
  186.         </div>  
  187.     </div>  
  188.     <div class="panel panel-danger">  
  189.         <div class="panel-heading"><b><p style="padding-left:50px;">Model and Stocks Information</p></b></div>  
  190.         <div style="width: 500px;">  
  191.             <div class="gridStyle" ng-grid="gridOptions"></div>  
  192.         </div>  
  193.     </div>  
  194. </body>  
  195.   
  196. </html>  
Output
 
When doing a grouping, the screen arranges the grouping by Name and Price.
 
Code Explanation
Added data to scope
  1. $scope.myData = [{ "Company""Samsung""Model""Samsung Galaxy Grand 2""Price": 5000, "Stocks": 4 },  
  2.                                          { "Company""Samsung""Model""Samsung Galaxy S3 Neo""Price": 9000, "Stocks": 41 },  
  3.                                        { "Company""Samsung""Model""Samsung Galaxy Grand Max""Price": 11000, "Stocks": 4 },  
  4.                                         { "Company""MicroMax""Model""Micromax Canvas Blaze""Price": 6300, "Stocks": 0 },  
  5.                                        { "Company""MicroMax""Model""Micromax Canvas Duddle""Price": 11000, "Stocks": 3 },  
  6.                                          { "Company""MicroMax""Model""Micromax Canvas Duddle- SPL""Price": 11000, "Stocks": 3 },  
  7.                                          { "Company""Blackberry""Model""Blackberry Z30""Price": 19000, "Stocks": 10 },  
  8.                                        { "Company""Blackberry""Model""Micromax bold  9780""Price": 12900, "Stocks": 20 },  
  9.   
  10.             ],  
We can add a different property to ng-grid, such as paging, sorting, pinning of columns we need to display, enable scrolling and controlling a cell property value such as styling and events.
  1. $scope.gridOptions = {  
  2.   
  3.                 data: 'myData',  
  4.                 pagingOptions: $scope.pagingOptions,  
  5.                 enablePinning: true,  
  6.                 enablePaging: true,  
  7.                 showFooter: true,  
  8.                 enableColumnResize: true,  
  9.                 enableCellSelection: true,  
  10.                 columnDefs: [  
  11.                         {  
  12.                             field: "Company",  
  13.                             width: 180,  
  14.                             pinned: true,  
  15.                             enableCellEdit: true  
  16.                         },  
  17.                         {  
  18.                             field: "Model",  
  19.                             width: 200,  
  20.                             enableCellEdit: true  
  21.                         },  
  22.                         {  
  23.                             field: "Price",  
  24.                             width: 100,  
  25.                             enableCellEdit: true  
  26.                         },  
  27.                         {  
  28.                             field: "Stocks",  
  29.                             width: 120,  
  30.                             enableCellEdit: true,  
  31.                             cellTemplate: basicCellTemplate  
  32.                         },  
  33.                         {  
  34.                             field: "Action",  
  35.                             width: 200,  
  36.                             enableCellEdit: false,  
  37.                             cellTemplate: '<button id="editBtn" type="button" class="btn btn-xs btn-info"  ng-click="updateCell()" >Click a Cell for Edit </button>'  
  38.                         }]  
  39.   
  40.             };  
Added the cell edit code on scope
  1. var basicCellTemplate = '<div class="ngCellText" ng-class="col.colIndex()" ng-click="editCell(row.entity, row.getProperty(col.field), col.field)"><span class="ui-disableSelection hover">{{row.getProperty(col.field)}}</span></div>';  
 Added the grouping code on scope and calling it on click of “CompanyByName and Price” button.
  1. $scope.changeGroupBy = function (group1, group2) {  
  2.   
  3. $scope.gridOptions.$gridScope.configGroups = [];  
  4.   
  5. $scope.gridOptions.$gridScope.configGroups.push(group1);  
  6.   
  7. $scope.gridOptions.$gridScope.configGroups.push(group2);  
  8.   
  9. $scope.gridOptions.groupBy();  
  10.   
  11. }
  12. ngGride
  13. fileuploadinangularjs  
  14. file upload in angularjs
  15. File upload in angularjs
  16. Server site validation display in client site MVC
  17. downloadimage

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>


Example of HttpClient

public List<ErrorDetail> CreateDocumentUDF(int registrationDocumentId, DocumentUDF documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{1}CreateDocumentUDF?registrationDocumentId={0}", registrationDocumentId, serviceUri);

            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.PostAsJsonAsync(requestUri, documentUDF); }).Result;
            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.Created:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUDF = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;
                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }

  public List<ErrorDetail> UpdateDocumentUDF(int registrationDocumentId, DocumentUDF documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{1}UpdateDocumentUDF?registrationDocumentId={0}", registrationDocumentId, serviceUri);
            //Asses the status code and return
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.PutAsJsonAsync(requestUri, documentUDF); }).Result;
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.NoContent:
                    //The call was successful, deserialize the response to a RegistrationDistrict list
                    documentUDF = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }

public List<ErrorDetail> DeleteDocumentUDF(int registrationDocumentId, int documentUDFMappingId)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{2}DeleteDocumentUDF?registrationDocumentId={0}&documentUdfMappingId={1}", registrationDocumentId, documentUDFMappingId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
               Task<HttpResponseMessage>.Run(async () => { return await mdsClient.DeleteAsync(requestUri); }).Result;
            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                //The call was successful, deserialize the response to a Zone list
                //No errors so return null
                case HttpStatusCode.NoContent:
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }
        }



public List<ErrorDetail> GetDocumentUDF(int registrationDocumentId, int languageId, out List<DocumentUDF> documentUDF)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{2}GetDocumentUDF?registrationDocumentId={0}&languageId={1}", registrationDocumentId, languageId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.GetAsync(requestUri); }).Result;

            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.OK:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUDF = serviceResponse.Content.ReadAsAsync<List<DocumentUDF>>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUDF = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }

        }



public List<ErrorDetail> GetDocumentUdfById(int registrationDocumentId, int udfId, int languageId, out DocumentUDF documentUdf)
        {
            //Form the appropriate request uri for this call
            var requestUri = String.Format("{3}GetDocumentUDFById?registrationDocumentId={0}&languageId={1}&udfId={2}", registrationDocumentId, languageId, udfId, serviceUri);
            //Make the get call to web service layer
            HttpResponseMessage serviceResponse =
                Task<HttpResponseMessage>.Run(async () => { return await mdsClient.GetAsync(requestUri); }).Result;

            //Asses the status code and return
            switch (serviceResponse.StatusCode)
            {
                case HttpStatusCode.OK:
                    //The call was successful, deserialize the response to a Property Document list
                    documentUdf = serviceResponse.Content.ReadAsAsync<DocumentUDF>().Result;
                    //No errors so return null
                    return null;

                default:
                    //if call have Error, deserialize the error list and return
                    documentUdf = null;
                    return serviceResponse.Content.ReadAsAsync<List<ErrorDetail>>().Result;
            }
        }


Monday, 2 October 2017

Example of all the validation(Required,StringLength,Compare,Range,RegularExpression,Custom) in Webapi and Angular js

First write a view  model in Webapi

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

namespace Implementwebapiinangularjs.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; }
        [Required(ErrorMessage = "Address should not be blank.")]
        public string ADDRESS { get; set; }
        [Required(ErrorMessage = "Password should not be blank.")]
        [StringLength(8, MinimumLength = 6, ErrorMessage = "Password length between 6 to 8.")]
        public string PASSWORD { get; set; }
        [Compare("PASSWORD", ErrorMessage = "Confirm password must be same as password.")]
        [Required(ErrorMessage = "Confimr password should not be blank.")]
        public string CP { get; set; }
        [Required(ErrorMessage = "Please select a gender.")]
        public string GENDER { get; set; }
        [Required(ErrorMessage = "Please select a hobby.")]
        public string HOBBY { get; set; }
        [Required(ErrorMessage = "Email should not be blank.")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid email id.")]
        public string EMAIL { get; set; }
        [Required(ErrorMessage = "Dob should not be blank.")]
[Customvalidation(ErrorMessage="Dob should not greater than or equal to current date.")]
        public DateTime? DOB { get; set; }
        [Required(ErrorMessage = "SALARY should not be blank.")]
        [Range(5000, 500000, ErrorMessage = "Salary range between 5000 to 500000.")]
        public decimal? SALARY { get; set; }
        [Required(ErrorMessage = "Please select a country.")]
        public int? CID { get; set; }
        [Required(ErrorMessage = "Please select a state.")]
        public int? SID { get; set; }

    }
}

public class Customvalidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null)
            return false;
        else
            return !(DateTime.Now.Subtract(((DateTime)value)).Days <= 0);
    }
}


Web Api

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

namespace WebApplication1.Controllers
{
    [RoutePrefix("api/Empservice")]
    public class EmpserviceController : ApiController
    {
        [HttpGet]
        [Route("Allcountry")]
        public IHttpActionResult Allcountry()
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.COUNTRies.ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpGet]
        [Route("Allstate/{CID:int}")]
        public IHttpActionResult Allstate(int CID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.STATEs.Where(m=>m.CID==CID).ToList());
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [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="Get")]
        public IHttpActionResult Emps(int EID)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    return Ok(obj.EMPs.Find(EID));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost]
        [Route("Save")]
        public IHttpActionResult Save(EMPVM vm)
        {
            try
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = new EMP();
                        emp.EID = vm.EID??0;
                        emp.NAME = vm.NAME;
                        emp.ADDRESS = vm.ADDRESS;
                        emp.PASSWORD = vm.PASSWORD;
                        emp.GENDER = vm.GENDER;
                        emp.EMAIL = vm.EMAIL;
                        emp.SALARY = vm.SALARY;
                        emp.DOB = vm.DOB;
                        emp.CID = vm.CID;
                        emp.SID = vm.SID;
                        obj.EMPs.Add(emp);
                        obj.SaveChanges();
                        return Created(new Uri(Url.Link("Get",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
            {
                using (Database1Entities obj = new Database1Entities())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        emp.NAME = vm.NAME;
                        emp.ADDRESS = vm.ADDRESS;
                        emp.PASSWORD = vm.PASSWORD;
                        emp.GENDER = vm.GENDER;
                        emp.EMAIL = vm.EMAIL;
                        emp.SALARY = vm.SALARY;
                        emp.DOB = vm.DOB;
                        emp.CID = vm.CID;
                        emp.SID = vm.SID;
                        obj.SaveChanges();
                        return Ok("Data Saved");
                    }
                    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())
                {
                    if (ModelState.IsValid)
                    {
                        EMP emp = obj.EMPs.Find(EID);
                        obj.EMPs.Remove(emp);
                        obj.SaveChanges();
                        return Ok("Data Deleted");
                    }
                    else
                        return BadRequest(ModelState);
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}


View in Angular Js


<!DOCTYPE html>
<html>
<head>
    <title></title>
<meta charset="utf-8" />
    <script src="angular.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />
    <script src="Scripts/angular-ui/ui-bootstrap.js"></script>
    <script src="Scripts/angular-ui/ui-bootstrap-tpls.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
    <div class="container" style="padding-top:10px">
        <div class="well">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="col-lg-4 control-label">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="col-lg-4 control-label">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="col-lg-4 control-label">ADDRESS</label>
                    <div class="col-lg-4">
                        <textarea class="form-control" ng-model="EMP.ADDRESS" ></textarea>
                        <span style="color:red" ng-bind="errAdd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">PASSWORD</label>
                    <div class="col-lg-4">
                        <input type="password" class="form-control" ng-model="EMP.PASSWORD" />
                        <span style="color:red" ng-bind="errPwd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">CONFIRM PASSWORD</label>
                    <div class="col-lg-4">
                        <input type="password" class="form-control" ng-model="EMP.CP" />
                        <span style="color:red" ng-bind="errCpwd"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">GENDER</label>
                    <div class="col-lg-4">
                        <input type="radio"  ng-model="EMP.GENDER" value="Male" />Male
                        <input type="radio" ng-model="EMP.GENDER" value="Female" />Female
                        <span style="color:red" ng-bind="errSex"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">HOBBY</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.HOBBY"  >
                            <option value="">Select</option>
                            <option value="Cricket">Cricket</option>
                            <option value="Football">Football</option>
                            <option value="Baseball">Baseball</option>
                            <option value="Hockey">Hockey</option>
                        </select>
                        <span style="color:red" ng-bind="errHobby"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">EMAIL</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.EMAIL" />
                        <span style="color:red" ng-bind="errEmail"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">DOB</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.DOB" />
                        <span style="color:red" ng-bind="errDob"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-lg-4 control-label">SALARY</label>
                    <div class="col-lg-4">
                        <input type="text" class="form-control" ng-model="EMP.SALARY" />
                        <span style="color:red" ng-bind="errSalary"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">COUNTRY</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.CID" ng-options="c.CID as c.CNAME for c in listc" ng-change="fillddl()" >
                            <option value="">Select</option>
                        </select>
                        <span style="color:red" ng-bind="errCid"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label">STATE</label>
                    <div class="col-lg-4">
                        <select class="form-control" ng-model="EMP.SID" ng-options="c.SID as c.SNAME for c in lists">
                            <option value="">Select</option>
                        </select>
                        <span style="color:red" ng-bind="errSid"></span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-lg-4 control-label"></label>
                    <div class="col-lg-4">
                        <input type="button" value="Save" style="width:80px" class="btn btn-primary" ng-click="save()" />
                        <input type="button" value="Update" style="width:80px" class="btn btn-primary" ng-click="update()" />
                        <input type="button" value="Reset" style="width:80px" class="btn btn-primary" ng-click="reset()" />
                    </div>
                </div>

            </form>
        </div>
        <div class="well">
            <div class="form-group">
                <label class="col-lg-1 control-label">SEARCH</label>
                <div class="col-lg-3">
                    <input type="text" placeholder="Search" uib-typeahead="c for c in listName| filter:$viewValue | limitTo:8" ng-model="search.NAME" class="form-control" />
              
                </div>
            </div>

            <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>GENDER</th>
                        <th>DOB</th>
                        <th>SALARY</th>
                        <th>(RS)SALARY</th>
                        <th>ACTION</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="c in liste|filter:search">
                        <td>{{c.EID|Eidfilter}}</td>
                        <td>{{c.NAME|uppercase}}</td>
                        <td>{{c.GENDER|lowercase}}</td>
                        <td>{{c.DOB|date:"dd-MMM-yyyy"}}</td>
                        <td>{{c.SALARY|number:2}}</td>
                        <td>{{c.SALARY|currency:'Rs. '}}</td>
                        <td>
                            <a ng-click="edit(c.EID)">Edit</a>|
                            <a ng-click="del(c.EID)">Delete</a>
                        </td>

                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", ['ui.bootstrap'])
    .controller("Ctrl", function ($scope, factoryEmp) {
        function CLR()
        {
            $scope.EMP = new emp();
            $scope.listName = [];
        } CLR();
        $scope.save = function ()
        {
            factoryEmp.Save($scope.EMP).error(function (ajXHR) {
                if (ajXHR.ModelState["eMPVM.EID"] != "")
                    $scope.errEid = ajXHR.ModelState["eMPVM.EID"];
                else
                    $scope.errEid = "";
                if (ajXHR.ModelState["eMPVM.NAME"] != "")
                    $scope.errName = ajXHR.ModelState["eMPVM.NAME"];
                else
                    $scope.errName = "";
                if (ajXHR.ModelState["eMPVM.ADDRESS"] != "")
                    $scope.errAdd = ajXHR.ModelState["eMPVM.ADDRESS"];
                else
                    $scope.errAdd = "";
                if (ajXHR.ModelState["eMPVM.PASSWORD"] != "")
                    $scope.errPwd = ajXHR.ModelState["eMPVM.PASSWORD"];
                else
                    $scope.errPwd = "";
                if (ajXHR.ModelState["eMPVM.CP"] != "")
                    $scope.errCpwd = ajXHR.ModelState["eMPVM.CP"];
                else
                    $scope.errCpwd = "";
                if (ajXHR.ModelState["eMPVM.GENDER"] != "")
                    $scope.errSex = ajXHR.ModelState["eMPVM.GENDER"];
                else
                    $scope.errSex = "";
                if (ajXHR.ModelState["eMPVM.HOBBY"] != "")
                    $scope.errHobby = ajXHR.ModelState["eMPVM.HOBBY"];
                else
                    $scope.errHobby = "";
                if (ajXHR.ModelState["eMPVM.EMAIL"] != "")
                    $scope.errEmail = ajXHR.ModelState["eMPVM.EMAIL"];
                else
                    $scope.errEmail = "";
                if (ajXHR.ModelState["eMPVM.DOB"] != "")
                    $scope.errDob = ajXHR.ModelState["eMPVM.DOB"];
                else
                    $scope.errDob = "";
                if (ajXHR.ModelState["eMPVM.SALARY"] != "")
                    $scope.errSalary = ajXHR.ModelState["eMPVM.SALARY"];
                else
                    $scope.errSalary = "";
                if (ajXHR.ModelState["eMPVM.CID"] != "")
                    $scope.errCid = ajXHR.ModelState["eMPVM.CID"];
                else
                    $scope.errCid = "";
                if (ajXHR.ModelState["eMPVM.SID"] != "")
                    $scope.errSid = ajXHR.ModelState["eMPVM.SID"];
                else
                    $scope.errSid = "";



                







            }).then(function (promise) {
                alert(promise.data);
                CLR();
                fill();
            });
        }
        factoryEmp.Getc().then(function (promise) {
            $scope.listc = promise.data;
        });
        function fx(s)
        {
            factoryEmp.Gets(s).then(function (promise) {
                $scope.lists = promise.data;
            });
        }
        $scope.fillddl = function ()
        {
            fx($scope.EMP.CID);
        }
        function fill()
        {
            factoryEmp.Gete().error(function (ajXHR) {
                alert(ajXHR.responseText);
            }).then(function (promise) {
                
                $scope.liste = promise.data;
                for (var i = 0; i < promise.data.length; i++)
                {
                    $scope.listName.push(promise.data[i].NAME);
                }
                
            });
        } fill();
        $scope.edit = function (s)
        {
            factoryEmp.Get(s).then(function (promise) {
                $scope.EMP = promise.data;
                fx($scope.EMP.CID);
                $scope.EMP.CP = $scope.EMP.PASSWORD;
                var dt=new Date($scope.EMP.DOB);
                $scope.EMP.DOB = (dt.getMonth() < 10 ? "0" + dt.getMonth() : dt.getMonth()) + "-" + (dt.getDate() < 10 ? "0" + dt.getDate() : dt.getDate()) + "-" + dt.getFullYear();
            });
        }
        $scope.reset = function ()
        {
            CLR();
        }
        $scope.update = function () {
            factoryEmp.Update($scope.EMP).error(function (ajXHR) {
                if (ajXHR.ModelState["eMPVM.EID"] != "")
                    $scope.errEid = ajXHR.ModelState["eMPVM.EID"];
                else
                    $scope.errEid = "";
                if (ajXHR.ModelState["eMPVM.NAME"] != "")
                    $scope.errName = ajXHR.ModelState["eMPVM.NAME"];
                else
                    $scope.errName = "";
                if (ajXHR.ModelState["eMPVM.ADDRESS"] != "")
                    $scope.errAdd = ajXHR.ModelState["eMPVM.ADDRESS"];
                else
                    $scope.errAdd = "";
                if (ajXHR.ModelState["eMPVM.PASSWORD"] != "")
                    $scope.errPwd = ajXHR.ModelState["eMPVM.PASSWORD"];
                else
                    $scope.errPwd = "";
                if (ajXHR.ModelState["eMPVM.CP"] != "")
                    $scope.errCpwd = ajXHR.ModelState["eMPVM.CP"];
                else
                    $scope.errCpwd = "";
                if (ajXHR.ModelState["eMPVM.GENDER"] != "")
                    $scope.errSex = ajXHR.ModelState["eMPVM.GENDER"];
                else
                    $scope.errSex = "";
                if (ajXHR.ModelState["eMPVM.HOBBY"] != "")
                    $scope.errHobby = ajXHR.ModelState["eMPVM.HOBBY"];
                else
                    $scope.errHobby = "";
                if (ajXHR.ModelState["eMPVM.EMAIL"] != "")
                    $scope.errEmail = ajXHR.ModelState["eMPVM.EMAIL"];
                else
                    $scope.errEmail = "";
                if (ajXHR.ModelState["eMPVM.DOB"] != "")
                    $scope.errDob = ajXHR.ModelState["eMPVM.DOB"];
                else
                    $scope.errDob = "";
                if (ajXHR.ModelState["eMPVM.SALARY"] != "")
                    $scope.errSalary = ajXHR.ModelState["eMPVM.SALARY"];
                else
                    $scope.errSalary = "";
                if (ajXHR.ModelState["eMPVM.CID"] != "")
                    $scope.errCid = ajXHR.ModelState["eMPVM.CID"];
                else
                    $scope.errCid = "";
                if (ajXHR.ModelState["eMPVM.SID"] != "")
                    $scope.errSid = ajXHR.ModelState["eMPVM.SID"];
                else
                    $scope.errSid = ""


            }).then(function (promise) {
                alert(promise.data);
                CLR();
                fill();
            });
        }
        $scope.del = function (s)
        {
            if (confirm('Do you want to delete it?'))
            {
                factoryEmp.Delete(s).then(function (promise) {
                    alert(promise.data);
                    fill();

                });

            }
        }
    })
        .filter("Eidfilter", function () {
            return function (x) {
                if (x == 1)
                    return "Siv1";
                else if (x == 2)
                    return "Sankar1";
                else
                    return "Mahadev1";
            }
        })
    .factory("factoryEmp", function ($http) {
        var fac = {};
        fac.Getc = function ()
        {
            return $http.get("http://localhost:5763/api/Empservies/AllCountry");
        }
        fac.Gets = function (CID) {
            return $http.get("http://localhost:5763/api/Empservies/AllState/"+CID);
        }
        fac.Save = function (EMP) {
            return $http.post("http://localhost:5763/api/Empservies/Save",EMP);
        }
        fac.Gete = function () {
            return $http.get("http://localhost:5763/api/Empservies/AllEmps");
        }
        fac.Get = function (EID) {
            return $http.get("http://localhost:5763/api/Empservies/AllEmp/"+EID);
        }
        fac.Update = function (EMP) {
            return $http.put("http://localhost:5763/api/Empservies/Update/"+EMP.EID, EMP);
        }
        fac.Delete = function (EID)
        {
            return $http.delete("http://localhost:5763/api/Empservies/Delete/" + EID);
        }


        return fac;
    });
    function emp()
    {
        return {
            EID: null,
            NAME: null,
            ADDRESS: null,
            PASSWORD: null,
            GENDER: null,
            HOBBY: null,
            EMAIL: null,
            DOB: null,
            SALARY: null,
            CID: null,
            SID:null
        }
    }
</script>