Pages

CRUD operation in mvc using jquery and ajax Part 1

Monday, 10 November 2014
This article will demonstrate how to perform CRUD operation in mvc using Entity Framework and Ajax.

Step 1- Create Empty MVC project.

Step 2- Create DataModel and DataContext Class.

using System.ComponentModel.DataAnnotations;

namespace MVCdataTables.Models
{
    public class Employee
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }
}

using System.Data.Entity;
namespace MVCdataTables.Models
{
    public class DemoDataContext:DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }
}

Step 2- Create a Controller Name as Home. and add the following method. Here GetEmployee will return list of employee.
public ActionResult Index()
        {
            return View();
        }
        public IList<Employee> GetEmployee()
        {
            IList<Employee> getData = _db.Employee.ToList();
            return getData;
        }

Step 3- For read operation, create a function in your controller which will json
 public JsonResult GetData()
        {
            return Json(GetEmployee());
        }

Step 4- Write following Js code to bind Employee table in your view
$(document).ready(function () {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/Home/GetData',
        dataType: "json",
        success: function (data) {
            BindTable(data);
        },
        error: function (data) {
            alert(data);
        }
    });
});

function BindTable(data) {
  var tabHtml = '';
  $.each(data, function (i, d) {
  tabHtml += "<tr><td><span class='hide'>" + d.ID + "</span>" + d.Name +"+</td>
    <td>" + d.Position + "</td><td>" + d.Age + "</td><td>" + d.Salary + "</td>"+"<td>
    <span class='Edit ML10'>Edit</span><span class='Delete ML10'>Delete</span> </tr>";
    });
    $('#dbTable').find('tbody').html(tabHtml);
    $('#dbTable').dataTable();
}

Step 5- Write following code in your view to show employee list in table.
<table id="dbTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Age</th>
        <th>Salary</th>
        <th>Action</th>
    </tr>
</thead>
    <tbody>
        
    </tbody>
</table>

step 6- Delete Operation. Write down following js .on click event of delete read the corresponding Employee .
$(document).delegate('.Delete', 'click', function () {
    var getId = parseInt($(this).closest('tr').find('td:eq(0)').find('span').text());
    BootstrapDialog.confirm('Are you sure you want to delete person?', function (result) {
            if (result) {
                $.ajax({
                    type: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    url: '/Home/DeleteData',
                    data: { Id: getId },
                    dataType: "json",
                    success: function (response) {
                        BindTable(response)
                    },
                    error: function (response) {
                        alert("Error In Deleting Person ");
                    }
                });
            }
        });
    });
Step 7- write down function in your controller to delete employee
 public JsonResult DeleteData(int Id)
        {
            var getPerson = _db.Employee.Find(Id);
            if (getPerson != null)
            {
                _db.Employee.Remove(getPerson);
                _db.SaveChanges();
            }
            return Json(GetEmployee(), JsonRequestBehavior.AllowGet);
        }



Note: You can download Js and Controller code from here Download

No comments:

Post a Comment