Friday 10 February 2017

DML oprations in Angular js


Api code :

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

namespace WebApplication1.Controllers
{
    public class EmpserviceController : ApiController
    {
        [HttpGet]
        public List<EMP> Gets()
        {
            using (Database1Entities obj = new Database1Entities())
            {
              
                return obj.EMPs.ToList();
            }
        }
        [HttpGet]
        public EMP1 Get(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return obj.EMPs.Select(x => new EMP1 { EID = x.EID, NAME = x.NAME, LPHONEMAP = obj.EMPPHONEMAPs.Where(m => m.EID == x.EID).Select(p => new EMPPHONE {PID= p.PID??0,NUMBER= p.NUMBER, LPHONE = obj.PHONEs.ToList() }).ToList() }).SingleOrDefault(P => P.EID == EID);
            }
        }
        [HttpPost]
        public string Post(EMP1 emp1)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                obj.EMPs.Add(new EMP { EID=emp1.EID,NAME=emp1.NAME });
                obj.SaveChanges();
                obj.EMPPHONEMAPs.AddRange(emp1.LPHONEMAP.Select(x => new  EMPPHONEMAP{ EID=emp1.EID, PID=x.PID,NUMBER=x.NUMBER }));
                obj.SaveChanges();
                return "Data Saved.";
            }
        }
        [HttpPut]
        public string Put(EMP1 emp1)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP emp = obj.EMPs.SingleOrDefault(m => m.EID == emp1.EID);
                emp.NAME = emp1.NAME;
                obj.SaveChanges();
                obj.EMPPHONEMAPs.RemoveRange(obj.EMPPHONEMAPs.Where(p => p.EID == emp1.EID));
                obj.SaveChanges();
                obj.EMPPHONEMAPs.AddRange(emp1.LPHONEMAP.Select(x => new EMPPHONEMAP { EID = emp1.EID, PID = x.PID, NUMBER = x.NUMBER }));
                obj.SaveChanges();
                return "Data Updated.";
            }
        }
        [HttpDelete]
        public string Delete(int EID)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                obj.EMPs.Remove(obj.EMPs.SingleOrDefault(m => m.EID == EID));
                obj.SaveChanges();
                obj.EMPPHONEMAPs.RemoveRange(obj.EMPPHONEMAPs.Where(p => p.EID == EID));
                obj.SaveChanges();
                obj.SaveChanges();
                return "Data Deleted.";
            }
        }
    }
    public class EMP1
    {
        public int EID{get;set;}
        public string NAME{get;set;}
        public List<EMPPHONE> LPHONEMAP { get; set; }
    }
    public class EMPPHONE
    {
        public int PID { get; set; }
        public string NUMBER { get; set; }
        public List<PHONE> LPHONE { get; set; }
    }
    
    
}

Angular js Code;

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="Content/bootstrap-theme.css" rel="stylesheet" />
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/angular.js"></script>
</head>
<body>
    <div class="container" ng-app="app" ng-controller="ctrl">
        <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="EMP1.EID" />
                </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="EMP1.NAME" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-4"></label>
                <div class="col-lg-4">
                    <table style="margin-top:10px">
                        <tr><td>Phone</td><td><a style="color:green;margin-left:303px" ng-click="add()">+</a></td></tr>
                    </table>
                    <table id="tb">
                        
                        <tr ng-repeat="c in EMP1.LPHONEMAP">
                            <td><select class="form-control" ng-model="c.PID" ng-options="d.PID as d.PHONETYPE for d in c.LPHONE"></select></td>
                            <td><input style="margin-left:10px" type="text" class="form-control" ng-model="c.NUMBER" /></td>
                            <td><a style="color:red;margin-left:20px" ng-click="sub(c)">-</a></td>
                        </tr>
                        <tr><td colspan="3">&nbsp;</td></tr>
                        
                    </table>
                </div>
            </div>
            <div class="form-group">
                <label class="col-lg-4">&nbsp;</label>
                <div class="col-lg-4">
                    <input type="button" ng-click="save()" class="btn btn-primary" value="Save" style="width:80px" />
                    <input type="button" ng-click="update()" class="btn btn-primary" value="Update" style="width:80px" />
                    <input type="button" ng-click="reset()" class="btn btn-primary" value="Reset" style="width:80px" />
                </div>
            </div>
            <div class="row">
                <table class="table table-bordered table-condensed table-hover table-responsive table-striped">
                    <thead class="bg-primary">
                        <tr>
                            <td>EID</td>
                            <td>NAME</td>
                            <td>ACTION</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="c in list1">
                            <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>
        </form>
       
    </div>
</body>
</html>
<script type="text/javascript">
    angular.module("app", [])
    .controller("ctrl", function ($scope, $http) {
        
        function fill1() {
            $http.get('http://localhost:57694/api/Empservice/Gets').then(function (d) {
                $scope.list1 = d.data;
            });
        } fill1();
        var n = [{ PID: 1, PHONETYPE: 'Mobile' }, { PID: 2, PHONETYPE: 'Land Line' }];
        $scope.add = function ()
        {
            $scope.EMP1.LPHONEMAP.push({ PID: null, NUMBER: null, LPHONE: n });
            
        }
        $scope.sub = function (s)
        {
            if ($scope.EMP1.LPHONEMAP.length > 1)
                $scope.EMP1.LPHONEMAP.splice($scope.EMP1.LPHONEMAP.indexOf(s), 1);
        }
        
       
        function CLR()
        {
            $scope.EMP1 = new eMP1();
        } CLR();
        $scope.save = function ()
        {
           
            $http.post('http://localhost:57694/api/Empservice/Post', $scope.EMP1).then(function (d) {
                alert(d.data);
                fill1();
                CLR();
            });
        }
        $scope.update = function ()
        {
            $http.put('http://localhost:57694/api/Empservice/Put', $scope.EMP1).then(function (d) {
                alert(d.data);
                fill1();
                CLR();
            });
        }
        $scope.edit = function (d)
        {
            $http.get('http://localhost:57694/api/Empservice/Get?EID='+d).then(function (d) {
                $scope.EMP1 = d.data;
                
            });
        }
        $scope.del = function (d)
        {
            if (confirm('Do you want to delete it ?'))
            {
                $http.delete('http://localhost:57694/api/Empservice/Delete?EID=' + d).then(function (d) {
                    
                    alert(d.data);
                    fill1();
                });
            }
        }
    });
    function eMP1()
    {
        return {
            EID: null,
            NAME: null,
            LPHONEMAP: [{
                PID: null,
                NUMBER: null,
                LPHONE:[{ PID: 1, PHONETYPE: 'Mobile' }, { PID: 2, PHONETYPE: 'Land Line' }]
            }]
        };
    }
</script>


Wednesday 1 February 2017

VIEW MODEL BIND IN JQUERY & MVC


Model :

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

namespace WebApplication27.Models
{
    public class EMP
    {
        public int EID { get; set; }
        public string NAME { get; set; }
    }
}

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

namespace WebApplication27.Models
{
    public class DEPT
    {
        public int? DID { get; set; }
        public string DNAME { get; set; }
    }
}


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

namespace WebApplication27.Models
{
    public class EMPVM
    {
        [Required(ErrorMessage = "EID should not blank.")]
        public int? EID { get; set; }
        [Required(ErrorMessage = "NAME should not blank.")]
        public string NAME { get; set; }
        [DisplayName("DEPARTMENT")]
        public List<DEPT> LDEPT { get; set; }
        [Required(ErrorMessage="DID should not blank.")]
        public int? DID { get; set; }
        [Required(ErrorMessage = "DNAME should not blank.")]
        public string DNAME { get; set; }
    }
}

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication27.Models;


namespace WebApplication27.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                return View(obj.EMP1.ToList());
            }
         
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(EMPVM emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                obj.EMP1.Add(new EMP1 { EID=emp.EID.Value,NAME=emp.NAME });
                obj.SaveChanges();
                if (emp.LDEPT != null)
                {
                    obj.DEPT1.AddRange(emp.LDEPT.Select(m => new DEPT1 { DID = m.DID.Value, DNAME = m.DNAME }));
                    obj.SaveChanges();
                    obj.EMPMAPs.AddRange(emp.LDEPT.Select(m => new EMPMAP { EID = emp.EID, DID = m.DID }));
                    obj.SaveChanges();
                }
                else
                {
                    obj.DEPT1.Add(new DEPT1 { DID = emp.DID.Value, DNAME = emp.DNAME });
                    obj.SaveChanges();
                    obj.EMPMAPs.Add( new EMPMAP { EID = emp.EID, DID = emp.DID });
                    obj.SaveChanges();
                }
                return RedirectToAction("Index");
            }
           
        }
        [HttpGet]
        public ActionResult Edit(int? id)
        {
            using (Database1Entities obj = new Database1Entities())
            {

                EMPVM emp = obj.EMP1.Where(a => a.EID == id).Select(x => new EMPVM { EID = x.EID, NAME = x.NAME, LDEPT = obj.DEPT1.Where(p => obj.EMPMAPs.Where(q => q.EID == id).Select(r => r.DID).Contains(p.DID)).Select(y => new DEPT { DID = y.DID, DNAME = y.DNAME }).ToList() }).FirstOrDefault();
                return View(emp);
            }
        }
     
        [HttpPost]
        public ActionResult Edit(EMPVM emp)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP1 emp1 = obj.EMP1.Find(emp.EID);
                emp1.NAME = emp.NAME;
                obj.SaveChanges();
                if (emp.LDEPT != null)
                {
                    var did = emp.LDEPT.Select(a => a.DID).ToList();
                    obj.DEPT1.RemoveRange(obj.DEPT1.Where(x => did.Contains(x.DID)));
                    obj.SaveChanges();
                    obj.DEPT1.AddRange(emp.LDEPT.Select(m => new DEPT1 { DID = m.DID.Value, DNAME = m.DNAME }));
                    obj.SaveChanges();
                    obj.EMPMAPs.RemoveRange(obj.EMPMAPs.Where(x => x.EID == emp.EID));
                    obj.SaveChanges();
                    obj.EMPMAPs.AddRange(emp.LDEPT.Select(m => new EMPMAP { EID = emp.EID, DID = m.DID }));
                    obj.SaveChanges();
                }
                else
                {
                    DEPT1 dept1 = obj.DEPT1.Find(emp.DID);
                    dept1.DNAME = emp.DNAME;
                    obj.SaveChanges();
                    EMPMAP eMPMAP = obj.EMPMAPs.Find(emp.EID);
                    eMPMAP.DID = emp.DID;
                    obj.SaveChanges();
                }
                return RedirectToAction("Index");
            }
        }
         [HttpGet]
        public ActionResult Delete(int? id)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                EMP1 emp1 = obj.EMP1.Find(id);
                return View(emp1);
            }
        }
         [HttpPost]
         public ActionResult Delete(EMP1 emp)
         {
             using (Database1Entities obj = new Database1Entities())
             {
                 obj.EMP1.Remove(obj.EMP1.Find(emp.EID));
                 obj.SaveChanges();
                 obj.EMPMAPs.RemoveRange(obj.EMPMAPs.Where(x => x.EID == emp.EID));
                 obj.SaveChanges();
                 return RedirectToAction("Index");
             }
         }
    }

}

View  :

Create View Code:

@model WebApplication27.Models.EMPVM

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
     
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.EID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LDEPT, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               <table id="tb">
                   <thead>
                       <tr><th>DID</th><th>DNAME</th><th><a id="add">+</a></th></tr>
                   </thead>
                   <tbody>
                       <tr class="c">
                           <td>
                               @Html.TextBoxFor(model => model.DID, new { @class = "form-control", @name="LDEPT[0].DID" } )
                               @Html.ValidationMessageFor(model => model.DID, "", new { @class = "text-danger" })
                           </td>
                           <td>
                               @Html.TextBoxFor(model => model.DNAME, new  { @class = "form-control", @name = "LDEPT[0].DNAME" } )
                               @Html.ValidationMessageFor(model => model.DNAME, "", new { @class = "text-danger" })
                           </td>
                           <td><a class="sub">-</a></td>
                       </tr>
                   </tbody>
               </table>
            </div>
        </div>

     

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>



<script type="text/javascript">

    $(function () {
        var i = 0;
        $('#add').click(function () {
            i++;
            $('#tb').append("<tr class='c'><td><input class ='form-control' type='text' name='LDEPT[" + i + "].DID' /></td><td><input type='text' class ='form-control' name='LDEPT[" + i + "].DNAME' /></td><td><a class='sub'>-</a></td></tr>");
            $('#tb').find('tr').each(function (p, j) {
                if (p > 0) {
                    var q = parseInt(p - 1);
                    $(j).find('td').each(function (k, l) {

                        if (k == 0) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DID")
                        }
                        else if (k == 1) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DNAME");
                        }


                    });
                }

            });


        });
        $('body').on("click", ".sub", function () {

            var row = $(this).parents('.c');
           if( $('#tb').find('tr').length>2)
            row.remove();
            $('#tb').find('tr').each(function (p, j) {
                if (p > 0) {
                    var q = parseInt(p - 1);
                    $(j).find('td').each(function (k, l) {
                        if (k == 0) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DID")
                        }
                        else if (k == 1) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DNAME");
                        }


                    });
                }

            });

        });

    });

</script>

Edit View Code :

@model WebApplication27.Models.EMPVM

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
      
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.EID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LDEPT, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <table id="tb">
                    <thead>
                        <tr><th>DID</th><th>DNAME</th><th><a id="add">+</a></th></tr>
                    </thead>
                    <tbody>
                        @for (int i = 0; i < Model.LDEPT.Count; i++)
                        {
                           
                            <tr class="c">
                                <td>
                                    @Html.TextBoxFor(model =>Model.LDEPT[i].DID,new { @class = "form-control", @name = "LDEPT['"+i+"'].DID" })
                                    @Html.ValidationMessageFor(model => model.DID, "", new { @class = "text-danger" })
                                </td>
                                <td>
                                    @Html.TextBoxFor(model => Model.LDEPT[i].DNAME, new { @class = "form-control", @name = "LDEPT['"+i+"'].DNAME" })
                                    @Html.ValidationMessageFor(model => model.DNAME, "", new { @class = "text-danger" })
                                </td>
                                <td><a class="sub">-</a></td>
                            </tr>
                        }
                        
                    </tbody>
                </table>
            </div>
        </div>



        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">

    $(function () {
        var i = 0;
        $('#add').click(function () {
            i++;
            $('#tb').append("<tr class='c'><td><input class ='form-control' type='text' name='LDEPT[" + i + "].DID' /></td><td><input type='text' class ='form-control' name='LDEPT[" + i + "].DNAME' /></td><td><a class='sub'>-</a></td></tr>");
            $('#tb').find('tr').each(function (p, j) {
                if (p > 0) {
                    var q = parseInt(p - 1);
                    $(j).find('td').each(function (k, l) {

                        if (k == 0) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DID")
                        }
                        else if (k == 1) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DNAME");
                        }


                    });
                }

            });


        });
        $('body').on("click", ".sub", function () {

            var row = $(this).parents('.c');
            if ($('#tb').find('tr').length > 2)
                row.remove();
            $('#tb').find('tr').each(function (p, j) {
                if (p > 0) {
                    var q = parseInt(p - 1);
                    $(j).find('td').each(function (k, l) {
                        if (k == 0) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DID")
                        }
                        else if (k == 1) {
                            $(l).find("input[type='text']").attr("name", "LDEPT[" + q + "].DNAME");
                        }


                    });
                }

            });

        });

    });
</script>

Delete View Code :


@model WebApplication27.Models.EMP1

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
  
    <hr />
    <dl class="dl-horizontal">
        <dt>
          
            @Html.DisplayNameFor(model => model.NAME)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.NAME)
        </dd>

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.EID)
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>


SOME RegularExpression example
[RegularExpression(@"^(\d{6,9})$", ErrorMessage = "Zip code will only accept numeric digits with length 6 digit")]
        [RegularExpression(@"\d{5}", ErrorMessage = "Zip code will only accept numeric digits with length 5 digit")]

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Please enter letters only")]


[RegularExpression(@"^(?=.*[A-Z])(?=.*\d)[A-Za-z\d!$%@#£€*?&]{8,16}$", ErrorMessage = "Password should be alpha-numeric, at least 8 characters long and have at least one number and one capital letter.")]