Monday, December 14, 2015

Curd in MVC with Angular JS

In this article I am going to explain CURD operation in MVC with Angular JS. you can follow given below steps and enjoy Angular js with  mvc.

Step 1

Go to File->New->Project (click on project).


After clicking on project a new window will be open and its look like



now select ASP.NET MVC4 Web Application and rename your solution name to "CurdInAngularMVC" and click on "OK"  button.


Step 2

After Complete Step 1 a new window will be open. select "Basic" template and  click on "OK" Button, output will look like



Step 3

Now right click at solution explorer  Click on "Manage NuGet Packages.." 



Click on "Manage NuGet Packages.." After clicking on it a window will be open , type in search box "angularjs" and click on install to searched angular js item, output is



Step 4

After Installing angularjs click on close button


Step 5

At the Solution explorer  in Script Floder , you may see angular js file has loaded. Now I edited "_Layout.cshtml" in "Views->Shared" folder.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
  
</head>
    @* Here  ng-app="MyApp" is used for auto-bootstrap an AngularJS application. here ng-app="MyApp" means <body> element is the owner
    of AngularJS application*@
<body ng-app="MyApp">
   
    <div style="height:1px; clear:both;"></div>
    @RenderBody()
    @Scripts.Render("~/bundles/jquery")
    @* Add Angular Library Here *@
    @Scripts.Render("~/bundles/angular")
    <script src="~/Scripts/MyApp.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

in it I added a "Scripts/MyApp.js" file. So this file added into Script folder with the name of "MyApp.js".

(function () {
    //Create a Module
    var app = angular.module('MyApp', ['ngRoute']);  // Will use ['ng-Route'] when we will implement routing
    //Create a Controller
    app.controller('CurdController'function ($scope) {  // here $scope is used for share data between view and controller
       
    });
})();

Step 6

Now I added a folder in Script folder name "AngularController" and after it a added a js file name ="CurdController.js"



CurdController.js

angular.module('MyApp')
.controller('CurdController', function ($scope, CurdService) { //inject CurdService
    $scope.submitText = "Save";
    $scope.submitted = false;
    $scope.message = '';
    $scope.isFormValid = false;
    $scope.EmpId = null;
    $scope.NAME = null;
    $scope.Mobile = null;
    $scope.empList = [];
    $scope.emp = {
        EmpId: '',
        NAME: '',
        Mobile: ''
    }
    $scope.edit = function (index) {
        $scope.emp.EmpId = index.EmpId;
        $scope.emp.NAME = index.NAME;
        $scope.emp.Mobile = index.Mobile;
    };
    $scope.clear = function () {
        $scope.emp.EmpId = '';
        $scope.emp.NAME = '';
        $scope.emp.Mobile = '';
    }
    //Check form Validation // here f1 is our form name
    $scope.$watch('f1.$valid', function (newValue) {
        $scope.isFormValid = newValue;
    });
    //for loading employee records in table
    CurdService.GeEmpContact().then(function (d) {
        $scope.empList = d.data; // Success
    }, function () {
        alert('Failed'); // Failed
    });
    //for delete
    $scope.delete = function (data) {
                var state = confirm("Do you want to delete this record");
                if (state == true)
                {
                    $.ajax({
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        //data: "{ id: "+data.id+" }",
                        data: JSON.stringify(data),
                        url: '/Curd/delete',
                        success: function (status) {
                         CurdService.GeEmpContact().then(function (d) {
                            $scope.empList = d.data; // Success
                        }, function () {
                            alert('Failed'); // Failed
                        });
                            console.log(status)
                        },
                        error: function (status) { }
                    });
                }
            }
            //for save and update
    $scope.SaveData = function (data) {
        if ($scope.submitText == 'Save') {
            $scope.submitted = true;
            $scope.message = '';
            if ($scope.isFormValid) {
                $scope.submitText = 'Please Wait...';
                CurdService.SaveFormData($scope.emp).then(function (d) {
                    alert(d);
                    if (d == 'Success') {
                        //have to clear form here
                        ClearForm();
                        CurdService.GeEmpContact().then(function (d) {
                            $scope.empList = d.data; // Success
                        }, function () {
                            alert('Failed'); // Failed
                        });
                    }
                    $scope.submitText = "Save";
                });
            }
            else {
                $scope.message = 'Please fill required fields value';
            }
        }
    }
    //Clear Form (reset)
    function ClearForm() {
        $scope.emp = {};
        $scope.f1.$setPristine(); //here f1 our form name
        $scope.submitted = false;
    }
})
.factory('CurdService', function ($http, $q) { // here I have created a factory which is a populer way to create and configure services
    var fac = {};
    fac.GeEmpContact = function () {
        return $http.get('/Curd/getList');
    }
    fac.SaveFormData = function (data) {
        var defer = $q.defer();
        $http({
            url: '/Curd/Save',//for save and update
            method: 'POST',
            data: JSON.stringify(data),
            headers: { 'content-type': 'application/json' }
        }).success(function (d) {
            // Success callback
            defer.resolve(d);
        }).error(function (e) {
            //Failed Callback
            alert('Error!');
            defer.reject(e);
        });
        return defer.promise;
    }
    return fac;
});


Step 8

Now i added a class at solution explorer  in "Model" folder  name as "Employee.cs"



Employee.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace CurdInAngularMVC.Models
{
    public class Employee
    {
        string Constr = ConfigurationManager.ConnectionStrings["mycon"].ToString();
        public int EmpId { get; set; }
        public string NAME { get; set; }
        public string Mobile { get; set; }
        public List<Employee> getList()
        {
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            var emp = new List<Employee>();
            string get = "select * from Employee";
            SqlCommand cmd = new SqlCommand(get, con);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Employee e = new Employee();
                e.EmpId = Convert.ToInt32(dr[0]);
                e.NAME = Convert.ToString(dr[1]);
                e.Mobile = Convert.ToString(dr[2]);
                emp.Add(e);
            }
            con.Close();
            return emp;
        }
        public int save()
        {
            int i = 0;
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_Curd", con);
            cmd.CommandType = CommandType.StoredProcedure;
            if (EmpId == 0)
            {
                cmd.Parameters.AddWithValue("@mode", "Ins");
            }
            else {
                cmd.Parameters.AddWithValue("@mode", "Update");
            }
            cmd.Parameters.AddWithValue("@EmpId", EmpId);
            cmd.Parameters.AddWithValue("@NAME", NAME);
            cmd.Parameters.AddWithValue("@Mobile", Mobile);
            i = cmd.ExecuteNonQuery();
            con.Close();
            return i;
        }
        public void delete(int data)
        {
            SqlConnection con = new SqlConnection(Constr);
            con.Open();
            string query = "delete from Employee where EmpId=@id";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@id", data);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Step 9

Now I added a controller  at Solution explorer in "Controllers" 




After Clicking on controller a new window will be open and rename controller name  to "CurdController" and click on Add button.



CurdController.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CurdInAngularMVC.Models;
namespace CurdInAngularMVC.Controllers
{
    public class CurdController : Controller
    {
        //
        // GET: /Curd/
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult getList()
        {
            var emp = new List<Employee>();
            Employee getdata = new Employee();
            emp = getdata.getList();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult Save(Employee data)
        {
            string message = string.Empty;
               Employee obj = new Employee();
               obj.EmpId = data.EmpId;
               obj.NAME = data.NAME;
               obj.Mobile = data.Mobile;
                int res = obj.save();
                if (res > 0)
                { message = "Success"; }
                else
                {
                    message = "Failed!";
                }
            return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        public JsonResult delete(Employee emp)
        {
            Employee del = new Employee();
            del.delete(emp.EmpId);
            return null;
        }
    }
}

Step 10

Now Right Click on Index Action result and add a view "Index.cshtml"

@{
    ViewBag.Title = "Index";
}
<style>
    input{
        padding:5px;
        border:1px solid #A5A5A5;
    }
    input.ng-dirty.ng-invalid {
        border:1px solid red;
        background-color:rgb(255, 244, 244);
    }
    .error {UserRole
        color:red;
    }
  
</style>
<h2>CURD in MVC with Angular JS</h2>
<div ng-controller="CurdController">
 <form novalidate name="f1" ng-submit="SaveData(emp)">
<div style="color:red">{{message}}</div>
<table>
<tr>
<td>EmployeeID:</td>
<td>
<input type="text" ng-model="emp.EmpId" name="pEmpId" ng-class="submitted?'ng-dirty':''" readonly />
 <span class="error" ng-show="(f1.pEmpId.$dirty || submitted) && f1.pEmpId.$error.required">Employee ID required!</span>
 </td>
 </tr>
 <tr>
<td>Name:</td>
<td>
<input type="text" ng-model="emp.NAME" name="pNAME" ng-class="submitted?'ng-dirty':''" required />
 <span class="error" ng-show="(f1.pNAME.$dirty || submitted) && f1.pNAME.$error.required">Name is Required.</span>
 </td>
 </tr>
 <tr>
<td>Mobile:</td>
<td>
<input type="text" ng-model="emp.Mobile" name="pMobile" ng-class="submitted?'ng-dirty':''" maxlength="13"/>
 </td>
 </tr>
 <tr>
<td></td>
<td>
<input type="submit" value="{{submitText}}" />
</td>
</tr>
</table>
</form>
<div style="text-align:center; width:400px">
<table class="table table-striped" >
    <thead>
        <tr>
            <th>Employee ID</th>
            <th>Name</th>
            <th>Mobile No</th>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="item in empList">
            <td>{{item.EmpId}}</td>
            <td>{{item.NAME}}</td>
            <td>{{item.Mobile}}</td>
            <td><input type="button" data-ng-click="edit(item)" value="Edit" /></td>
            <td><input type="button" data-ng-click="delete(item)" value="Delete" /></td>
        </tr>
    </tbody>
</table>
    </div>
</div>
@section scripts{
    <script src="../../Scripts/AngularController/CurdController.js"></script>
}


Database script

table script

CREATE TABLE Employee (
                EmpId INT NOT NULL identity(1, 1) PRIMARY KEY,
                NAME VARCHAR(50) NOT NULL,
                Mobile VARCHAR(13)
                )
Procedure script
-- =============================================
-- Author:                              Sharad Gupta
-- Create date: 12-Dec-2015
-- Description:       Insert update delete in table Employee
-- =============================================
CREATE PROCEDURE usp_Curd (
                @EmpId INT,
                @mode VARCHAR(30),
                @NAME VARCHAR(50),
                @Mobile VARCHAR(13) = ''
                )
AS
BEGIN
                IF (@mode = 'Ins')
                BEGIN
                                INSERT INTO Employee (
                                                NAME,
                                                Mobile
                                                )
                                VALUES (
                                                @NAME,
                                                @Mobile
                                                )
                END
                IF (@mode = 'Update')
                BEGIN
                                UPDATE Employee
                                SET NAME = @NAME,
                                                Mobile = @Mobile
                                WHERE EmpId = @EmpId
                END
END
GO

Now Some changes made in "App_Start" folder files

"BundleConfig.cs"

using System.Web;
using System.Web.Optimization;
namespace LoginPageMVCWithAngularJS
{
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/angular").Include(
                  "~/Scripts/angular.js",
                  "~/Scripts/angular-route.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
        }
    }
}

Now Edited in "RouteConfig.cs"


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LoginPageMVCWithAngularJS
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional }
            );
        }
    }
}

Now  Run your application.


No comments:

Post a Comment