Monday, March 12, 2018

MVC Demo With Grid Paging,Sorting,Serching

===============================
Home Controller - Controller
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UniqDataMvc.DataService;
using UniqDataMvc.Models;

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

        public ActionResult GetEmployees()
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                //dalc dc = new dalc();
                //var employees = dc.EmployeeMasters.OrderBy(a => a.Name).ToList();
                //return Json(new { data = employees }, JsonRequestBehavior.AllowGet);

                List<EmployeeMaster> emp = new dalc().selectbyquerydt("select E.*,D.DepName As DepartmentName from EmployeeMaster as E inner join departmentMaster as D on D.DepId=E.depId").ConvertToList<EmployeeMaster>().ToList();
                return Json(new { data = emp }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpGet]
        public ActionResult Save(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                ViewBag.deptList = dc.departmentMasters.ToList();
                return View(v);
            }
        }

        public ActionResult Save(EmployeeMaster emp)
        {
            bool status = false;
            if (ModelState.IsValid)
            {
                using (VensystemMvcEntities dc = new VensystemMvcEntities())
                {
                    if (emp.EmpId > 0)
                    {
                        //Edit
                        var v = dc.EmployeeMasters.Where(a => a.EmpId == emp.EmpId).FirstOrDefault();
                        if (v != null)
                        {
                            v.Name = emp.Name;
                            v.Email = emp.Email;
                            v.MobileNo = emp.MobileNo;
                            v.depId = emp.depId;
                            v.Birthdate = emp.Birthdate;
                        }
                    }
                    else
                    {
                        //Save
                        dc.EmployeeMasters.Add(emp);
                    }
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                EmployeeMaster v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    return View(v);
                }
                else
                {
                    return HttpNotFound();
                }
            }
        }

        [HttpPost]
        [ActionName("Delete")]
        public ActionResult DeleteEmployee(int id)
        {
            bool status = false;
            using (VensystemMvcEntities dc = new VensystemMvcEntities())
            {
                var v = dc.EmployeeMasters.Where(a => a.EmpId == id).FirstOrDefault();
                if (v != null)
                {
                    dc.EmployeeMasters.Remove(v);
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }
    }
}
===============================
Model Class -- CLass
===============================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace UniqDataMvc.Models
{
    [MetadataType(typeof(EmployeeMetadata))]
    public partial class EmployeeMaster
    {
        public string DepartmentName { get; set; }
    }

    public class EmployeeMetadata
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide first name")]
        public string Name { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please Select department")]
        public int depId { get; set; }

        [Required(ErrorMessage = "Email Required.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Email is not valid")]
        public string Email { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Mobile No")]
        public string MobileNo { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please provide Birthdate")]
        public string Birthdate { get; set; }
    }
}
===============================
Index.cshtml - List -- View
===============================

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
    <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
    <style>
        span.field-validation-error {
            color: red;
        }
    </style>
</head>
<body>
    <div style="width:90%; margin:0 auto" class="tablecontainer">
        <a class="popup btn btn-primary" href="/home/save/0" style="margin-bottom:20px; margin-top:20px;">Add New Employee</a>
        <table id="myDatatable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>dep Name</th>
                    <th>Email</th>
                    <th>MobileNo</th>
                    <th>Birthdate</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </thead>
        </table>
    </div>

    <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

    <script>
        $(document).ready(function () {
            var oTable = $('#myDatatable').DataTable({
                "ajax": {
                    "url" : '/home/GetEmployees',
                    "type" : "get",
                    "datatype" : "json"
                },
                "pageLength": 5,
                "columns": [
                    { "data": "Name", "autoWidth": true },
                    //{ "data": "depId", "autoWidth" : true},
                    { "data": "DepartmentName", "autoWidth": true},
                    { "data": "Email", "autoWidth": true },
                    { "data": "MobileNo", "autoWidth": true },
                    { "data": "Birthdate", "autoWidth": true },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/save/'+data+'">Edit</a>';
                        }
                    },
                    {
                        "data": "EmpId", "width": "50px", "render": function (data) {
                            return '<a class="popup" href="/home/delete/' + data + '">Delete</a>';
                        }
                    }
                ]
            })
            $('.tablecontainer').on('click', 'a.popup', function (e) {
                debugger
                e.preventDefault();
                OpenPopup($(this).attr('href'));
            })
            function OpenPopup(pageUrl) {
                debugger
                var $pageContent = $('<div/>');
                $pageContent.load(pageUrl, function () {
                    $('#popupForm', $pageContent).removeData('validator');
                    $('#popupForm', $pageContent).removeData('unobtrusiveValidation');
                   // $.validator.unobtrusive.parse('form');

                });

                $dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
                          .html($pageContent)
                          .dialog({
                              draggable : false,
                              autoOpen : false,
                              resizable : false,
                              model : true,
                              title:'Popup Dialog',
                              height : 550,
                              width : 600,
                              close: function () {
                                  $dialog.dialog('destroy').remove();
                              }
                          })

                $('.popupWindow').on('submit', '#popupForm', function (e) {
                    debugger
                    var url = $('#popupForm')[0].action;
                    $.ajax({
                        type : "POST",
                        url : url,
                        data: $('#popupForm').serialize(),
                        success: function (data) {
                            if (data.status) {
                                $dialog.dialog('close');
                                oTable.ajax.reload();
                            }
                        }
                    })

                    e.preventDefault();
                })

                $dialog.dialog('open');
            }
        })
    </script>
</body>
</html>
===============================
Save.cshtml - IU Functionality -- View
===============================
@model UniqDataMvc.Models.EmployeeMaster

<h2>Save</h2>

@using (Html.BeginForm("save", "home", FormMethod.Post, new { id = "popupForm" }))
{
    if (Model != null && Model.EmpId > 0)
    {
        @Html.HiddenFor(a => a.EmpId)
    }

    <div class="form-group">
        <label>First Name</label>
        @Html.TextBoxFor(a => a.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Name)
    </div>
    <div class="form-group">
        <label>Department Name</label>
        @Html.DropDownListFor(x => x.depId, new SelectList(ViewBag.deptList, "DepId", "DepName"), "Select", htmlAttributes: new { @class = "select form-control" })
        @Html.ValidationMessageFor(a => a.depId)
    </div>
    <div class="form-group">
        <label>Email</label>
        @Html.TextBoxFor(a => a.Email, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.Email)
    </div>
    <div class="form-group">
        <label>MobileNo</label>
        @Html.TextBoxFor(a => a.MobileNo, new { @class = "form-control" })
        @Html.ValidationMessageFor(a => a.MobileNo)
    </div>
    <div class="form-group">
        <label>Birthdate</label>
        @Html.TextBoxFor(a => a.Birthdate, new { @class = "form-control",type="date" })
        @Html.ValidationMessageFor(a => a.Birthdate)
    </div>
 

    <div>
        <input type="submit" value="Save" />
    </div>
}

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
===============================
CommonFunction - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CommmanFunction
    {
        public static List<T> ConvertToList<T>(this DataTable dt)
        {
            List<T> data = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T item = GetItem<T>(row);
                data.Add(item);
            }
            return data;
        }
        public static T GetItem<T>(DataRow dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            foreach (DataColumn column in dr.Table.Columns)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name == column.ColumnName)
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(dr[column.ColumnName])))
                        {
                            if (pro.PropertyType.Name == "String")
                                pro.SetValue(obj, Convert.ToString(dr[column.ColumnName]));
                            else
                                pro.SetValue(obj, dr[column.ColumnName]);
                        }
                    }
                    else
                        continue;
                }
            }
            return obj;
        }
    }
}
===============================
CreatePara - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace UniqDataMvc.DataService
{
    public static class CreatePara
    {
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, string paraVal, int size = 50, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.Size = size;
            para.SqlDbType = System.Data.SqlDbType.NVarChar;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, int paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Int;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, decimal paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Decimal;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, float paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Float;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, DateTime paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.DateTime;
            para.Direction = dir;
            return para;
        }
        public static SqlParameter CreateParameter(this SqlParameter para, string paraName, System.Data.DataTable paraVal, ParameterDirection dir = ParameterDirection.Input)
        {
            para.ParameterName = paraName;
            para.Value = paraVal;
            para.SqlDbType = System.Data.SqlDbType.Structured;
            para.Direction = dir;
            return para;
        }
    }
}
===============================
Dalc - -- DataServices
===============================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;

namespace UniqDataMvc.DataService
{
    public class dalc
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dalc_Conn"].ConnectionString);
        // SqlConnection conn;

        public dalc()
        {
            //conn.ConnectionString = ConfigurationSettings.AppSettings["myconn"];


            // conn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

        }

        public DataSet selectbyquery(string str)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

        public DataTable selectbyquerydt(string str)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 0;
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = str.ToString();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            try
            {
                conn.Open();
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Dispose();
            }
        }

       
    }
}

Thursday, March 30, 2017

Cart system with angular js

------------------------------------------
Cntrl.cs
------------------------------------------
public class CartController : Controller
    {
        DemoEntities context = new DemoEntities();
        // GET: Cart
        public ActionResult Index()
        {
            ViewBag.Productlist = context.ProductMasters.ToList();
            return View();
        }
        public ActionResult CartView()
        {
            return View();
        }
    }
------------------------------------------
srvc.js
------------------------------------------
(function () {
    angular.module("myapp").service("CartService", ["$http", function ($http) {

        var listing = [];
        listing.GetAllProduct = function () {
            return $http({
                method: "Post",
                url: "",
                data: "",
            })
        }
    }])
})();
------------------------------------------
Cntrl.js
------------------------------------------
(function () {
    angular.module("myapp", []).controller("CartCntrl", ["$scope", "$http", "CartService", function CartCntrl($scope, $http, CartService) {
        $scope.cartlist = JSON.parse(localStorage.getItem("Cart")) == null ? [] : JSON.parse(localStorage.getItem("Cart"));
        $scope.cartviewlist = [];
        $scope.price = 0;
        $scope.counting = 0
        $scope.GetProduct = function (data) {
            $scope.Productlist = angular.copy(data);
            $.each($scope.cartlist, function (index, value) {
                $scope.price += parseInt(value.Price);
                $scope.counting += parseInt(value.Quantity);
            })
        }

        $scope.AddCart = function (data) {
            var Cart = [];
            if (localStorage.length > 0) {
                $scope.cartlist = JSON.parse(localStorage.getItem("Cart"));
            }
            if ($scope.counting != data.Quantity) {
                $scope.cartlist.push({
                    ProductName: data.ProductName,
                    ProductImage: data.ProductImage,
                    ProductDesc: data.ProductDesc,
                    Price: data.Price,
                    Quantity: 1,
                    OrignalPrice: data.Price,
                    OrignalQuantity: data.Quantity
                });
                $scope.price += parseInt(data.Price);
                $scope.counting++;
                $scope.priceing = $scope.price;
                $scope.counteing = $scope.counting;
                localStorage.setItem("Cart", JSON.stringify($scope.cartlist))
            } else {
                alert("Maximum " + data.Quantity + " Allowed.");
            }
        }
        function counttotal() {
            $scope.priceing = 0;
            $scope.counteing = 0;
            $.each($scope.cartviewlist, function (index, value) {
                $scope.priceing += parseInt(value.Price);
                $scope.counteing += parseInt(value.Quantity);
            })
        }
        $scope.ViewCartData = function () {
            $scope.cartlist = JSON.parse(localStorage.getItem("Cart"));
            var isDuplicate = false;
            $.each($scope.cartlist, function (index, value) {
                var data = jQuery.grep($scope.cartviewlist, function (val, cartindex) {
                    if (val.ProductName == value.ProductName) {
                        $scope.cartviewlist[cartindex].Quantity += 1;
                        $scope.cartviewlist[cartindex].Price += value.Price;
                    }
                    return val.ProductName == value.ProductName
                });
                if (data.length <= 0) {
                    $scope.cartviewlist.push(value);
                }
                counttotal();
            });
        }
     
        //$scope.ViewCartData();
        $scope.removeitem = function (index) {
            $scope.cartviewlist[index].Quantity = $scope.cartviewlist[index].Quantity - 1;
            $scope.cartviewlist[index].Price = $scope.cartviewlist[index].Price - $scope.cartviewlist[index].OrignalPrice;
            localStorage.setItem("Cart", JSON.stringify($scope.cartviewlist));
            counttotal();
         
            //$scope.cartviewlist[index].Price = $scope.cartviewlist[index].Quantity - 1;
        }
        $scope.additem = function (index) {
                $scope.cartviewlist[index].Quantity = $scope.cartviewlist[index].Quantity + 1;
                $scope.cartviewlist[index].Price = $scope.cartviewlist[index].Price + $scope.cartviewlist[index].OrignalPrice;
                localStorage.setItem("Cart", JSON.stringify($scope.cartviewlist));
                counttotal();

            //$scope.cartviewlist[index].Price = $scope.cartviewlist[index].Quantity - 1;
        }
        $scope.Remove = function (index) {
            $scope.cartviewlist.splice(index, 1);
            localStorage.setItem("Cart", JSON.stringify($scope.cartviewlist));
            counttotal();
        }
     
    }])
})();
------------------------------------------
Index.cshtml
------------------------------------------

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /><br />
<div data-ng-controller="CartCntrl">
    <div data-ng-init="GetProduct(@Json.Encode(ViewBag.Productlist))">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>
                        Sr.
                    </th>
                    <th>
                        Image
                    </th>
                    <th>
                        ProductName
                    </th>
                    <th>
                        ProductDesc
                    </th>
                    <th>
                        Price
                    </th>
                    <th>
                        Quantity
                    </th>
                    <th>
                        <a href="/Cart/CartView"><b>{{counting}} items, Rs.{{price}}</b></a>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in Productlist" ng-if="Productlist.length >0">
                    <td>
                        {{$index+1}}
                    </td>
                    <td>
                        <img src="~/Content/Img/{{item.ProductImage}}" />
                    </td>
                    <td>
                        {{item.ProductName}}
                    </td>
                    <td>
                        {{item.ProductDesc}}
                    </td>
                    <td>
                        {{item.Price}}
                    </td>
                    <td>
                        {{item.Quantity}}
                    </td>
                    <td>
                        <a href="#" ng-click="AddCart(item)">Add To Cart</a>
                    </td>
                </tr>
                <tr ng-if="Productlist.length <= 0" class="text-danger">
                    <td colspan="8"> <span class="text-danger text-center"> Record not found.</span> </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/Controller/CartCntrl.js"></script>
    <script src="~/Scripts/Services/CartService.js"></script>
    @*<script>
        $(window).load(function () {
            localStorage.removeItem("Cart");
        })
    </script>*@
}
------------------------------------------
cartview.cshtml
------------------------------------------

@{
    ViewBag.Title = "CartView";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /><br />
<div ng-controller="CartCntrl">
    <div ng-init="ViewCartData()">
        <div>
            <a href="/Cart/Index" class="btn btn-primary">Back</a>
        </div>
        <br />
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>
                        Sr.
                    </th>
                    <th>
                        ProductName
                    </th>
                    <th>
                        Price
                    </th>
                    <th>
                        Quantity
                    </th>
                    <th>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in cartviewlist" ng-if="cartviewlist.length >0">
                    <td>
                        {{$index+1}}
                    </td>
                    <td>
                        {{item.ProductName}}
                    </td>
                    <td>
                         Rs.{{item.Price}}
                    </td>
                    <td>
                        {{item.Quantity}} <a ng-if="item.Quantity<item.OrignalQuantity" class="btn btn-default" ng-click="additem($index)">+</a><a class="btn btn-default" ng-if="item.Quantity>1" ng-click="removeitem($index)">-</a>
                    </td>
                    <td>
                        <a href="#" ng-click="Remove($index)">X</a>
                    </td>
                </tr><tr>
                         <td>
                         </td>
                         <td>
                         </td>
                         <td>
                            Rs.{{priceing}}
                         </td>
                         <td>
                             {{counteing}}
                         </td>
                </tr>
                <tr ng-if="cartviewlist.length <= 0" class="text-danger">
                    <td colspan="8"> <span class="text-danger text-center"> Record not found.</span> </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/Controller/CartCntrl.js"></script>
    <script src="~/Scripts/Services/CartService.js"></script>
}
------------------------------------------
table
------------------------------------------
ProductId int Unchecked
ProductName varchar(50) Unchecked
ProductDesc nvarchar(200) Checked
ProductImage nvarchar(50) Checked
Price decimal(18, 2) Unchecked
Quantity int Unchecked

Tuesday, March 28, 2017

Angular js Demo

----------------------------------------------------
angularjs setup install
layout html=> data-ng-app="myapp"
layout head=> <script src="https://use.fontawesome.com/bc3ab0b857.js"></script>
layou body=> <script src="~/Scripts/angular.min.js"></script>
----------------------------------------------------

index.cshtml
----------------------------------------------------


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /><br />
<div>
    <div data-ng-controller="DefultController">
        <div class="row" ng-init="Departmentbind(@Json.Encode(ViewBag.DepartData),@Json.Encode(ViewBag.StudentData))">
            <form role="form" id="frmstudent" name="frmstudent" ng-class="{'submitted':submitted}" ng-submit="submitted=true" novalidate>
                <div class="row">
                    <div class="col-md-4 col-md-offset-4">
                        <div class="form-group">
                            <label>Name :</label>
                            <input data-ng-model="objstudent.Name" id="Name" name="Name" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Name is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>BirthDate :</label>
                            <input type="date" data-ng-model="objstudent.BirthDate" id="Birthdate" name="Birthdate" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Birthdate is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Department :</label>
                            <select data-ng-model="objstudent.DepartmentId" id="DepartmentId" name="DepartmentId" class="form-control" required data-ng-options="dm.DepartmentId as dm.DepartmentName for dm in Departmentlist">
                                <option value="">---Select---</option>
                            </select>
                            <span class="text-danger" ng-if="submitted && objstudent.DepartmentId==''"><i class="fa fa-exclamation-triangle"></i> Department is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Gender :</label>
                            <input type="radio" ng-model="objstudent.Gender" value="1" name="Gender1" required />Male
                            <input type="radio" ng-model="objstudent.Gender" value="2" name="Gender1" required />Female
                            <br />
                            <span class="text-danger" ng-if="submitted && objstudent.Gender==''"><i class="fa fa-exclamation-triangle"></i> Gender is Required.!</span>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-default" data-ng-click="frmstudent.$valid && createupdate(objstudent)">Submit</button>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" ng-model="search" class="form-control" placeholder="Search" style="max-width: 100%;"><span class="input-group-addon">
                                    <span class="glyphicon glyphicon-search"></span>
                                </span>
                            </div>

                            <br />
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th ng-click="sort('Name')" style="cursor:pointer;">
                                            Name <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('BirthDate')" style="cursor:pointer;">
                                            BirthDate <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Department')" style="cursor:pointer;">
                                            Department <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Gender')" style="cursor:pointer;">
                                            Gender <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th>
                                            Action
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="studnt in Studentlist|filter:search|orderBy:sortKey:reverse">
                                        <td>
                                            {{studnt.Name}}
                                        </td>
                                        <td>
                                            {{studnt.BirthDate | date :  "dd-MMM-yyyy"}}
                                        </td>
                                        <td>
                                            {{studnt.Department}}
                                        </td>
                                        <td>
                                            {{studnt.Gender==1?"Male":"Female"}}
                                        </td>
                                        <td>
                                            <a ng-click="Edit(studnt)" style="cursor:pointer;" title="Edit" data-tooltip="Edit"><i class="fa fa-edit"></i></a>
                                            <a ng-click="Delete(studnt.StudentId)" style="cursor:pointer;" title="Delete" data-tooltip="Delete"><i class="fa fa-trash pr2"></i></a>
                                        </td>
                                    </tr>
                                    <tr ng-if="Studentlist==null || Studentlist.length <=0">
                                        <td class="col-md-4 col-md-offset-4">
                                            <label class="text-danger">Record Not Found.</label>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <ul class="pagination pagination-sm">
                                <li ng-class="{active:0}">
                                    <a href="#" ng-click="firstPage()">First</a>
                                </li>
                                <li ng-repeat="n in range(ItemsByPage.length)">
                                    <a href="#" ng-click="setPage()" ng-bind="n+1">1</a>
                                </li>
                                <li>
                                    <a href="#" ng-click="lastPage()">Last</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/Controller/DefultController.js"></script>
    <script src="~/Scripts/Services/DefultService.js"></script>
}


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /><br />
<div>
    <div data-ng-controller="DefultController">
        <div class="row" ng-init="Departmentbind(@Json.Encode(ViewBag.DepartData),@Json.Encode(ViewBag.StudentData))">
            <form role="form" id="frmstudent" name="frmstudent" ng-class="{'submitted':submitted}" ng-submit="submitted=true" novalidate>
                <div class="row">
                    <div class="col-md-4 col-md-offset-4">
                        <div class="form-group">
                            <label>Name :</label>
                            <input data-ng-model="objstudent.Name" id="Name" name="Name" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Name is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>BirthDate :</label>
                            <input type="date" data-ng-model="objstudent.BirthDate" id="Birthdate" name="Birthdate" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Birthdate is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Department :</label>
                            <select data-ng-model="objstudent.DepartmentId" id="DepartmentId" name="DepartmentId" class="form-control" required data-ng-options="dm.DepartmentId as dm.DepartmentName for dm in Departmentlist">
                                <option value="">---Select---</option>
                            </select>
                            <span class="text-danger" ng-if="submitted && objstudent.DepartmentId==''"><i class="fa fa-exclamation-triangle"></i> Department is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Gender :</label>
                            <input type="radio" ng-model="objstudent.Gender" value="1" name="Gender1" required />Male
                            <input type="radio" ng-model="objstudent.Gender" value="2" name="Gender1" required />Female
                            <br />
                            <span class="text-danger" ng-if="submitted && objstudent.Gender==''"><i class="fa fa-exclamation-triangle"></i> Gender is Required.!</span>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-default" data-ng-click="frmstudent.$valid && createupdate(objstudent)">Submit</button>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" ng-model="search" class="form-control" placeholder="Search" style="max-width: 100%;"><span class="input-group-addon">
                                    <span class="glyphicon glyphicon-search"></span>
                                </span>
                            </div>

                            <br />
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th ng-click="sort('Name')" style="cursor:pointer;">
                                            Name <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('BirthDate')" style="cursor:pointer;">
                                            BirthDate <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Department')" style="cursor:pointer;">
                                            Department <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Gender')" style="cursor:pointer;">
                                            Gender <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th>
                                            Action
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="studnt in Studentlist|filter:search|orderBy:sortKey:reverse">
                                        <td>
                                            {{studnt.Name}}
                                        </td>
                                        <td>
                                            {{studnt.BirthDate | date :  "dd-MMM-yyyy"}}
                                        </td>
                                        <td>
                                            {{studnt.Department}}
                                        </td>
                                        <td>
                                            {{studnt.Gender==1?"Male":"Female"}}
                                        </td>
                                        <td>
                                            <a ng-click="Edit(studnt)" style="cursor:pointer;" title="Edit" data-tooltip="Edit"><i class="fa fa-edit"></i></a>
                                            <a ng-click="Delete(studnt.StudentId)" style="cursor:pointer;" title="Delete" data-tooltip="Delete"><i class="fa fa-trash pr2"></i></a>
                                        </td>
                                    </tr>
                                    <tr ng-if="Studentlist==null || Studentlist.length <=0">
                                        <td class="col-md-4 col-md-offset-4">
                                            <label class="text-danger">Record Not Found.</label>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <ul class="pagination pagination-sm">
                                <li ng-class="{active:0}">
                                    <a href="#" ng-click="firstPage()">First</a>
                                </li>
                                <li ng-repeat="n in range(ItemsByPage.length)">
                                    <a href="#" ng-click="setPage()" ng-bind="n+1">1</a>
                                </li>
                                <li>
                                    <a href="#" ng-click="lastPage()">Last</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/Controller/DefultController.js"></script>
    <script src="~/Scripts/Services/DefultService.js"></script>
}


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br /><br />
<div>
    <div data-ng-controller="DefultController">
        <div class="row" ng-init="Departmentbind(@Json.Encode(ViewBag.DepartData),@Json.Encode(ViewBag.StudentData))">
            <form role="form" id="frmstudent" name="frmstudent" ng-class="{'submitted':submitted}" ng-submit="submitted=true" novalidate>
                <div class="row">
                    <div class="col-md-4 col-md-offset-4">
                        <div class="form-group">
                            <label>Name :</label>
                            <input data-ng-model="objstudent.Name" id="Name" name="Name" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Name is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>BirthDate :</label>
                            <input type="date" data-ng-model="objstudent.BirthDate" id="Birthdate" name="Birthdate" class="form-control" required />
                            <span class="text-danger" ng-if="submitted && frmstudent.Name.$error.required"><i class="fa fa-exclamation-triangle"></i> Birthdate is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Department :</label>
                            <select data-ng-model="objstudent.DepartmentId" id="DepartmentId" name="DepartmentId" class="form-control" required data-ng-options="dm.DepartmentId as dm.DepartmentName for dm in Departmentlist">
                                <option value="">---Select---</option>
                            </select>
                            <span class="text-danger" ng-if="submitted && objstudent.DepartmentId==''"><i class="fa fa-exclamation-triangle"></i> Department is Required.!</span>
                        </div>
                        <div class="form-group">
                            <label>Gender :</label>
                            <input type="radio" ng-model="objstudent.Gender" value="1" name="Gender1" required />Male
                            <input type="radio" ng-model="objstudent.Gender" value="2" name="Gender1" required />Female
                            <br />
                            <span class="text-danger" ng-if="submitted && objstudent.Gender==''"><i class="fa fa-exclamation-triangle"></i> Gender is Required.!</span>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-default" data-ng-click="frmstudent.$valid && createupdate(objstudent)">Submit</button>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" ng-model="search" class="form-control" placeholder="Search" style="max-width: 100%;"><span class="input-group-addon">
                                    <span class="glyphicon glyphicon-search"></span>
                                </span>
                            </div>

                            <br />
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th ng-click="sort('Name')" style="cursor:pointer;">
                                            Name <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('BirthDate')" style="cursor:pointer;">
                                            BirthDate <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Department')" style="cursor:pointer;">
                                            Department <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th ng-click="sort('Gender')" style="cursor:pointer;">
                                            Gender <i class="fa fa-sort" aria-hidden="true"></i>
                                        </th>
                                        <th>
                                            Action
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="studnt in Studentlist|filter:search|orderBy:sortKey:reverse">
                                        <td>
                                            {{studnt.Name}}
                                        </td>
                                        <td>
                                            {{studnt.BirthDate | date :  "dd-MMM-yyyy"}}
                                        </td>
                                        <td>
                                            {{studnt.Department}}
                                        </td>
                                        <td>
                                            {{studnt.Gender==1?"Male":"Female"}}
                                        </td>
                                        <td>
                                            <a ng-click="Edit(studnt)" style="cursor:pointer;" title="Edit" data-tooltip="Edit"><i class="fa fa-edit"></i></a>
                                            <a ng-click="Delete(studnt.StudentId)" style="cursor:pointer;" title="Delete" data-tooltip="Delete"><i class="fa fa-trash pr2"></i></a>
                                        </td>
                                    </tr>
                                    <tr ng-if="Studentlist==null || Studentlist.length <=0">
                                        <td class="col-md-4 col-md-offset-4">
                                            <label class="text-danger">Record Not Found.</label>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                            <ul class="pagination pagination-sm">
                                <li ng-class="{active:0}">
                                    <a href="#" ng-click="firstPage()">First</a>
                                </li>
                                <li ng-repeat="n in range(ItemsByPage.length)">
                                    <a href="#" ng-click="setPage()" ng-bind="n+1">1</a>
                                </li>
                                <li>
                                    <a href="#" ng-click="lastPage()">Last</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@section Scripts{
    <script src="~/Scripts/Controller/DefultController.js"></script>
    <script src="~/Scripts/Services/DefultService.js"></script>
}


----------------------------------------------------
cntrl.js
----------------------------------------------------

(function () {
    angular.module("myapp", [])
        .controller("DefultController", [
        "$scope", "$http", "DefultService", "$filter",
        function DefultController($scope, $http, DefultService, $filter) {
            $scope.objstudent = {
                StudentId: 0,
                Name: '',
                BirthDate: new Date(),
                DepartmentId: '',
                DepartmentName: '',
                Gender: '',
            }
            $scope.currentPage = 0;
            $scope.pageSize = 2;
            $scope.createupdate = function (data) {
                DefultService.CreateUpdate(data).then(function (result) {
                    if (result.data != null) {
                        alert(result.data);
                        window.location.href = "/Default/Index";
                    }
                })
            }
            //$scope.search = function () {
            //    $scope.filteredList = filteredListService.searched($scope.allItems, $scope.searchText);
            //    if ($scope.searchText == '') {
            //        $scope.filteredList = $scope.allItems;
            //    }
            //    $scope.pagination();
            //}
            $scope.pagination = function () {
                $scope.ItemsByPage = filteredListService.paged($scope.filteredList, $scope.pageSize);
            };
            $scope.setPage = function () {
                $scope.currentPage = this.n;
            };
            $scope.firstPage = function () {
                $scope.currentPage = 0;
            };
            $scope.lastPage = function () {
                $scope.currentPage = $scope.ItemsByPage.length - 1;
            };
            $scope.range = function (input, total) {
                var ret = [];
                if (!total) {
                    total = input;
                    input = 0;
                }
                for (var i = input; i < total; i++) {
                    if (i != 0 && i != total - 1) {
                        ret.push(i);
                    }
                }
                return ret;
            };


            $scope.sort = function (keyname) {
                $scope.sortKey = keyname;   //set the sortKey to the param passed
                $scope.reverse = !$scope.reverse; //if true make it false and vice versa
            }
            $scope.Departmentbind = function (data, stdData) {
                $scope.Departmentlist = JSON.parse(data);
                $scope.Studentlist = JSON.parse(stdData);
            }
            $scope.Edit = function (data) {
                //data.Gender = data.Gender.toString();
                $scope.objstudent = angular.copy(data);
                //$scope.objstudent.Name = data.Name;
                $scope.objstudent.Gender = data.Gender.toString();
                $scope.objstudent.BirthDate = new Date(data.BirthDate);
                //$scope.objstudent.DepartmentId = data.DepartmentId;
                //$scope.objstudent.DepartmentName = data.Department;

            }
            $scope.Delete = function (id) {
                if (confirm("are you sure to delete?")) {
                    DefultService.Delete(id).then(function (result) {
                        if (result.data != null) {
                            alert(result.data);
                            window.location.href = "/Default/Index";
                        }
                    })
                }
            }
        }]);


    //.controller("DefultController", function () {
    //    console.log("Data");
    //})
    //.controller("DefultController", [
    //    "$scope", "$http", "DefultService", function DefultController($scope, $http, DefultService) {
    //    $scope.objstudent = {
    //        StudentId: 0,
    //        Name: '',
    //        Birthdate: '',
    //        DepartmentId: 0,
    //        DepartmentName: '',
    //        Gender: '',
    //    }
    //    $scope.createupdate = function (data) {

    //    }
    //    $scope.Departmentbind = function (data) {
    //        //DefultService.GetDepartment().then(function (result) {
    //        $scope.Departmentlist = data;
    //        //})
    //    }

    //}]);
})()

----------------------------------------------------
service.js
----------------------------------------------------
(function () {
    angular.module("myapp")
        .service("DefultService", [
        "$http",
        function ($http) {
            var listing = {};
            listing.CreateUpdate = function (obj) {
                return $http({
                    method: "POST",
                    url: "/Default/CreateUpdate",
                    data: obj
                })
            };
            listing.Delete = function (id) {
                return $http({
                    method: "POST",
                    url: "/Default/Delete?id=" + id,
                })
            };
            return listing;
        }])
})()



----------------------------------------------------
cntrl.cs
----------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using AngularJs_Demo.Models;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace AngularJs_Demo.Controllers
{
    public class DefaultController : Controller
    {
        DemoEntities contextt = new DemoEntities();
        // GET: Default
        public ActionResult Index()
        {
            List<DepartmentMaster> obj = new List<DepartmentMaster>();
            obj = contextt.DepartmentMasters.ToList();
            var qry = contextt.StudentMasters.Join(
                      contextt.DepartmentMasters,
                      post => post.DepartmentId,
                      meta => meta.DepartmentId,
                      (post, meta) => new { Post = post, Meta = meta }).ToList();
            List<StudentMaster> std = contextt.StudentMasters.Where(x => x.IsActive == true).ToList();
            int i = 0;
            foreach (var dpt in qry)
            {
                if (std.Count > 0 && std.Count > i)
                {
                    if (std[i].DepartmentId == dpt.Meta.DepartmentId)
                    {
                        std[i].Department = dpt.Meta.DepartmentName;
                        i++;
                    }
                    //std[i].DepartmentName = dpt.DepartmentName;
                }
            }
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            ViewBag.DepartData = JsonConvert.SerializeObject(obj,
                                 Formatting.None,
                                 new JsonSerializerSettings()
                                 {
                                     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                 });
            ViewBag.StudentData = JsonConvert.SerializeObject(std,
                                  Formatting.None,
                                  new JsonSerializerSettings()
                                  {
                                      ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                  });
            return View();
        }
        [HttpPost]
        public JsonResult CreateUpdate(StudentMaster obj)
        {
            int error = 0;
            string msg = "";
            obj.IsActive = true;
            if (obj.StudentId > 0)
            {
                StudentMaster objstd = contextt.StudentMasters.Find(obj.StudentId);
                objstd.DepartmentId = obj.DepartmentId;
                objstd.Name = obj.Name;
                objstd.BirthDate = obj.BirthDate;
                objstd.Gender = obj.Gender;
                contextt.Entry(objstd).State = System.Data.Entity.EntityState.Modified;
                contextt.SaveChanges();
                error = 1;
            }
            else
            {
                contextt.StudentMasters.Add(obj);
                contextt.SaveChanges();
                error = 1;
            }
            if (error == 1)
            {
                msg = "Data Saved Successfully.";
            }
            else
            {
                msg = "Data Not Saved.";
            }
            return Json(msg);
        }
        public JsonResult Delete(int id)
        {
            int error = 0;
            string msg = "";
            if (id > 0)
            {
                StudentMaster objstd = contextt.StudentMasters.Find(id);
                objstd.IsActive = false;
                contextt.Entry(objstd).State = System.Data.Entity.EntityState.Modified;
                contextt.SaveChanges();
                error = 1;
            }
            if (error == 1)
            {
                msg = "Data Deleted Successfully.";
            }
            else
            {
                msg = "Data Not Deleted.";
            }
            return Json(msg);
        }
    }
}

Demo for Repository Pattern in ASP.Net

----------------------------------------------------------- ----------------------------------------------------------- Repository Projec...