Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Retrieve data in asp.net MVC tab without reloading the parent page or full page load?

I want to use multiple tabs and on click of specific tab want to retrieve data using partial view not require full page post.

<ul class="nav nav-tabs">
 <li class="active"><a href="#FirstTab" data-toggle="tab" aria-expanded="true">First </a></li>
<li class=""><a href="#SecondTab " data-toggle="tab" aria-expanded="false">second </a></li>
<li class=""><a href="#ThirdTab" data-toggle="tab" aria-expanded="false">Third </a></li>
</ul>
<div class="tab-content">
    <!--/.tab-pane -->
 <div class="tab-pane active" id="FirstTab">
     <!-- /.first tab starts here -->
     </div>
    <!--/.tab-pane -->
    <div class="tab-pane" id="Secondtab">
   <!-- /.second tab starts here -->
 
    </div>
     <!--/.tab-pane -->
 
          <div class="tab-pane" id="ThirdTab">
       <!-- /.third tab starts here -->
 
          </div>
         <!--/.tab-pane -->
         </div>
            <!--/.tab-content -->
        </div>

CRUD Operation in ASP.NET MVC and AngularJS

Insert,Update,Delete in AngularJS and ASP.NET MVC 

In this post I will create sample Asp.net MVC 4 application using AngularJS and perform

CRUD (Create, Read, Update and Delete) operations using SPA (Single Page Application).

First create Asp.net MVC 4 application named “AngularMVC” and then simply follow below steps.

1.  Now create a new Employee class in model folder with name as Employee.cs and add below listed properties.

   public class Employee
     {
 
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
     }


2. Now create entity EmployeeContext.cs class in model folder.

  namespace AngularMVC.Models
  {
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("DefaultConnection")
        {
        }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EmployeeContext>(null);
        }
        public DbSet<Employee> EmployeeData { get; set; }
    }
  }


3. Now let's add following code in HomeController to Retrieve, Insert, Update and delete Employee records.

       // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmployeeContext contextObj = new EmployeeContext()))
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
 
        // Insert/ADD new employee
        public JsonResult Save(Employee data)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var EmployeeList = contextObj.EmployeeData.Add(data);
                contextObj.SaveChanges();
            }
            return null;
 
        }
 
        // Update existing employee
        public JsonResult Update(int id,string name,string email,string address)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id ==  id).FirstOrDefault();
                employeeList.Name = name;
                employeeList.Email = email;
                employeeList.Address = address;
               
                contextObj.SaveChanges();
            }
            return null;
        }
 
        // Delete existing employee
        public JsonResult Delete(int id)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id == id).FirstOrDefault();
                contextObj.EmployeeData.Remove(employeeList);
                contextObj.SaveChanges();
            }
            return null;
        }
 

4. Change existing connection string or Add database connection in web.config.

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=SampleAngularMVCDb;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

5. Go to Scripts and create a new folder as EmployeeScripts, under EmployeeScripts folder create 3 new js files as AngApp.js, EmpController.js & EmpService.js.

 

6. Now under shared folder there is view named _Layout.cshtm, add all these scripts files in that shared view.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script src="~/EmployeeScripts/js/angular.min.js"></script>
        <script src="~/EmployeeScripts/js/AngApp.js"></script>
        <script src="~/EmployeeScripts/js/EmpController.js"></script>
        <script src="~/EmployeeScripts/js/EmpService.js"></script>
    </head>
   <body>
….
</body>
</html>


7. Now let’s create view named Index.cshtml with AngularJS code under folder Home, then add ng-app,ng-controller,ng-model,ng-repeat,ng-click AnularJS directives in this view with required html code.

 @{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="EmpApp" ng-controller="EmpCntrlr">
   
        <table border="1" cellpadding="10" align="center">
 
            <tr>
                <td colspan="4">
                    <form name="myForm" novalidate>
                        <table>
                            <tr>
                                <td>
                                    <input type="hidden" id="txtid" name="id" ng-model="employeeData.Id" />
                                </td>
                                <td>
                                    Name:
                                    <input type="text" id="txtEmpName" name="name" ng-model="employeeData.Name" />
                                </td>
                                <td>
                                    Email:
                                    <input type="email" id="txtEmpEmail" name="email" ng-model="employeeData.Email" />
                                    <span ng-show="myForm.email.$error.email">Invalid email address.</span>
                                </td>
                                <td>
                                    Address:
                                    <input type="text" id="txtEmpAddress" name="address" ng-model="employeeData.Address" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" style="text-align:right">
                                    <button ng-click="myForm.$valid && Save()">Save</button>
                                   
                                </td>
                            </tr>
                        </table>
                    </form>
          </td>
            </tr>
 
            <tr>
                <th>
                   
                </th>
                <th>
                    Name
                </th>
                <th>
                    Email
                </th>
                <th>
                    Address
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Id'">
 
                <td>
                </td>
                <td>
                    <input type="text" id="txtName" ng-model="emp.Name" />
                </td>
                <td>
                    <input type="text" id="txtem" ng-model="emp.Email" />
                </td>
                <td>
                    <input type="text" id="txtadd" ng-model="emp.Address" />
                </td>
                <td>
                    <button ng-click="Delete(emp.Id)">Delete</button>
                </td>
                <td>
                    <button ng-click="Update(emp.Id,emp.Name,emp.Email,emp.Address)">Update</button>
                </td>
            </tr>
        </table>
</div>
 


8. Open AngApp.js and define angular module as below

var app = angular.module("EmpApp", []);

9. Open EmpService.js and define functions for CRUD (insert, update, delete) operations on Employee.

app.service("EmployeeService", function ($http) {
 
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
    // Delete Employee by Id
    this.DeleteEmployee = function (EmpID) {
        var response = $http({
            method: "post",
            url: "Home/Delete",
            params: {
                id: EmpID
            }
        });
        return response;
    }
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
            }
        });
        return response;
    }
});

 

10.  Open EmpController.js and all required functions(i.e clear(),setdefaultdata() etc) with CRUD operations.

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
 
    $scope.employeeData= {
 
        id: 0,
 
        Name: 'nagnath',
 
        Email: 'test@gmail.com',
 
        Address: 'ok'
 
    }
 
    $scope.Save = function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify($scope.employeeData),
            url: '/Home/Save',
            success: function (data, status) {
                ClearFields();
                GetAllEmployee();
            },
            error: function (status) { }
        });
    }
 
     // Angular ajax function deletes employee data for selected employee
       $scope.Delete = function (EmpId) {
        debugger;
        var DelEmployee = EmployeeService.DeleteEmployee(EmpId);
        DelEmployee.then(function (empls) {
            ClearFields();
            GetAllEmployee();
        }, function () {
            alert('Employee data not found');
        });
       }
    // Angular ajax function Update employee data for selected employee
       $scope.Update = function (Id,Name,Email,Address) {
           debugger;
           var UpdateEmployeeData = EmployeeService.UpdateEmployee(Id, Name, Email, Address);
           UpdateEmployeeData.then(function (empls) {
               ClearFields();
               GetAllEmployee();
           }, function () {
               alert('Employee data not found');
           });
       }
 
    function ClearFields() {
        $scope.Name = "";
        $scope.Email = "";
        $scope.Address = "";
      
    }
 
});
 

Final Page Look 


ASP.NET MVC with AngularJS

AngularJS with ASP.NET MVC 

I have already shared post on AngularJS with asp.net CRUD operations but in this post I am going to share Basic example that retrieves data from database and display it using AngularJS,Asp.net MVC and Entity framework.

AngularJS

AngularJS is a JavaScript framework open-source client-side web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Following are some angular directives I used in this example

ng-app

Declares the root element of an AngularJS application, under which directives can be used to declare bindings and define behavior.

ng-controller

Specifies a JavaScript controller class that evaluates HTML expressions.

ng-repeat

Instantiate an element once per item from a collection.

AngularJS with ASP.NET MVC Example

In layout section I added reference to angularJS controller,service code.

Layout:

<!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")
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="~/Content/js/AngApp.js"></script>
    <script src="~/Content/js/Employee.js"></script>
    <script src="~/Content/js/Service.js"></script>
</head>
<body>
    @RenderBody()
 
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Asp.net MVC View and AngularJS View

 @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
 <div ng-app="EmpApp" ng-controller="EmpCntrlr">
        <table border="1" cellpadding="10" align="center" class="table table-bordered table-striped">
            <tr>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Name'">
 
                <td>
                    {{emp.Id}}
                </td>
                <td>
                    {{emp.Name}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                 {{emp.EmailId}}
                </td>
            </tr>
        </table>        
         </div>

 

Asp.net Entity framework and Model

 

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace AngularMvcApp.Models
{
    public class EmolyeeDbContext : DbContext  {
        public EmolyeeDbContext(): base("DefaultConnection")      { }
   protected override void OnModelCreating(DbModelBuilder modelBuilder)      {         Database.SetInitializer<EmolyeeDbContext>(null);    }
        public DbSet<EmployeeData> EmployeeData { get; set; }
    }
}

 

Asp.net Employee Model

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; 
 
namespace AngularMvcApp.Models
{
public class EmployeeData
    {
        [Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }  }
}

 

Asp.net MVC Controller

using AngularMvcApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            return View();
        }
        // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmolyeeDbContext contextObj = new EmolyeeDbContext())
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

 

AngularJS Model

var app = angular.module("EmpApp", []);

AngularJS Controller

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
});

AngularJS Service

app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
});

धन्यवाद !!!