Crud operation using Ajax in ASP.NET MVC

1. Crud operation using Ajax in ASP.NET MVC

i) Create a table 


ii) Create a new application in VS 

iii) Add  new Ado.net entity data model class in the model 

iv)select EF Designer from the database

v) Add new Connection

vi) select server and database name then click on ok

Click on next

vii) select entity framework version then select next

viii) choose the database object which do you want to include in your model then select finish

ix) Build the solution

x) update /install  jquery and datepicker using Nuget package Manger

xi) install jquery

xii) install bootstrap datepicker

install jquery ui

xiii) Add Controller named employee

xiv) Add Mvc 5 controller empty


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using CrudOperationUsingAjax.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace CrudOperationUsingAjax.Controllers
{
    public class EmployeeController : Controller
    {
        private technosysEntities db = new technosysEntities();
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult List()
        {
            var list = db.employees.ToList();
            var data = (from e in db.employees.AsEnumerable()
                        select new
                        {
                            emplyee_id = e.emplyee_id,
                            employee_name = e.employee_name,
                            email_id = e.email_id,
                            mobile_no = e.mobile_no,
                            joining_date = e.joining_date.ToString("dd/MM/yyyy"),
                            address = e.address,
                            is_active = e.is_active
                        }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult Add(employee empObj)
        {
            empObj.is_active = true;
            db.employees.Add(empObj);
            db.SaveChanges();
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetbyID(int ID)
        { var list = db.employees.FirstOrDefault(x => x.emplyee_id == ID);
            return Json(new
            {
                emplyee_id = list.emplyee_id,
                employee_name = list.employee_name,
                email_id = list.email_id,
                mobile_no = list.mobile_no,
                joining_date = list.joining_date.ToString("dd/MM/yyyy"),
                address = list.address,
                is_active = list.is_active
            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Update(employee obj)
        {
            var data = db.employees.FirstOrDefault(x => x.emplyee_id == obj.emplyee_id);
            if (data != null)
            {
                data.employee_name = obj.employee_name;
                data.email_id = obj.email_id;
                data.mobile_no = obj.mobile_no;
                data.joining_date = obj.joining_date;
                data.address = obj.address;
                data.is_active = obj.is_active;
                db.Entry(data).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            return Json(JsonRequestBehavior.AllowGet);
        }
        public JsonResult Delete(int ID)
        {
            var data = db.employees.FirstOrDefault(x => x.emplyee_id == ID);
            db.employees.Remove(data);
            db.SaveChanges();
            return Json(JsonRequestBehavior.AllowGet);
        }
    }
}

xv) Add index view


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
@model IEnumerable<CrudOperationUsingAjax.Models.employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container">
    <h2>Users Record</h2>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Add</button><br /><br />
    <div id="tbod"></div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="myModalLabel">Add Employee</h4>
            </div>
            <div class="modal-body">
                <form>
                    <input type="hidden" id="emplyee_id" />
                    <div class="form-group">
                        <label for="Name">Employee Name</label>
                        <input type="text" class="form-control" id="employee_name" placeholder="employee_name" />
                    </div>
                    <div class="form-group">
                        <label for="Age">Email ID</label>
                        <input type="text" class="form-control" id="email_id" placeholder="email_id" />
                    </div>
                    <div class="form-group">
                        <label for="State">Mobile No</label>
                        <input type="text" class="form-control" id="mobile_no" placeholder="mobile_no" />
                    </div>
                    <div class="form-group">
                        <label for="Country">Joining Date</label>
                        <div class="cal-icon">
                            <input class="datepicker" placeholder="From Date" type="text" id="joining_date" name="joining_date">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="Country">Address</label>
                        <input type="text" class="form-control" id="address" placeholder="address" />
                    </div>
                    <div class="col-md-4" id="DivIsActive" style="display:none;margin-top: 40px;">
                        <div class="form-group">
                            <label for="is_active"> Enable</label>
                            <input id="is_active" name="is_active" type="checkbox">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btnAdd" onclick="Add()">Submit</button>
                <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.5.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/Users.js"></script>

<script>
    $(document).ready(function () {
        $(".datepicker").datepicker({ dateFormat: "dd/mm/yy", changeMonth: true, changeYear: true, buttonText: "Select", showOn:'both' }).val()
        loadData();
    });
    function loadData() {
        $.ajax({
            url: "/Employee/List",
            type: "GET",
            success: function (result) {
                debugger
                console.log(result);
                var $table = $('<table/>');
                $table.append('<thead><tr><th style="width:20%">Employee Name</th><th style="width:20%">Email id</th><th style="width:10%">Mobile No</th><th style="width:10%">Joining Date</th><th style="width:10%">Address</th><th style="width:10%">Status</th><th style="width:10%">Acion</th></tr></thead>');
                var $tbody = $('<tbody/>');
                $.each(result, function (key, item) {
                    var $row = $('<tr/>');
                    $row.append($('<td/>').html(item.employee_name));
                    $row.append($('<td/>').html(item.email_id));
                    $row.append($('<td/>').html(item.mobile_no));
                    $row.append($('<td/>').html((item.joining_date)));
                    $row.append($('<td/>').html(item.address));
                    if (item.is_active == true) { $row.append($('<td/>').html("Active")); } else { $row.append($('<td/>').html("InActive")); }
                    var $Action = $('<a href="#" onclick="getbyID(' + item.emplyee_id + ')">Edit</a> | <a href="#" onclick="Delele(' + item.emplyee_id + ')">Delete</a>');
                    $row.append($('<td/>').html($Action));
                    $tbody.append($row);
                });
                $table.append($tbody);
                $("#tbod").html($table);
                //alert(html);
                //$("#tbod").html(html);
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }
    function Add() {
        debugger;
        var res = validate();
        if (res == true) {


            var empObj = {
                employee_name: $('#employee_name').val(),
                email_id: $('#email_id').val(),
                mobile_no: $('#mobile_no').val(),
                joining_date: $('#joining_date').val(),
                address: $('#address').val(),
            };

            $.ajax({
                url: "/Employee/Add",
                type: "POST",
                data: empObj,
                success: function (result) {
                    $('#myModal').modal('hide');
                    loadData();
                    
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
            clearTextBox();
        }
        else {
            return false;
        }
    }
    function getbyID(Id) {
        $('#employee_name').css('border-color', 'lightgrey');
        $('#email_id').css('border-color', 'lightgrey');
        $('#mobile_no').css('border-color', 'lightgrey');
        $('#joining_date').css('border-color', 'lightgrey');
        $('#address').css('border-color', 'lightgrey');
        $('#is_active').css('border-color', 'is_active');
        $.ajax({
            url: "/Employee/getbyID/" + Id,
            typr: "GET",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (result) {
                $('#emplyee_id').val(result.emplyee_id);
                $('#employee_name').val(result.employee_name);
                $('#email_id').val(result.email_id);
                $('#mobile_no').val(result.mobile_no);
                $('#joining_date').val(result.joining_date);
                $('#address').val(result.address);
                if (result.is_active == true) { $('#is_active').prop('checked', true); } else { $('#is_active').prop('checked', false); }
                //$('#is_active').val(result.is_active);
                $('#myModal').modal('show');
                $('#DivIsActive').show();
                $('#btnUpdate').show();
                $('#btnAdd').hide();
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
        return false;
    }
    function Update() {
        var res = validate();
        if (res == true) {
            var is_active = false
            if ($('#is_active').is(":checked")) {
                is_active = true;
            }
            else {
                is_active = false;
            }
            var empObj = {
                emplyee_id: $('#emplyee_id').val(),
                employee_name: $('#employee_name').val(),
                email_id: $('#email_id').val(),
                mobile_no: $('#mobile_no').val(),
                joining_date: $('#joining_date').val(),
                address: $('#address').val(),
                is_active: is_active,
            };
            $.ajax({
                url: "/Employee/Update",
                data: JSON.stringify(empObj),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    $('#myModal').modal('hide');
                    $('#emplyee_id').val("");
                    $('#employee_name').val("");
                    $('#email_id').val("");
                    $('#mobile_no').val("");
                    $('#joining_date').val("");
                    $('#address').val("");
                    loadData();
                    
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
            clearTextBox();
        }
    }
    function Delele(ID) {
        var ans = confirm("Are you sure you want to delete this Record?");
        if (ans) {
            $.ajax({
                url: "/Employee/Delete/" + ID,
                type: "POST",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                success: function (result) {
                    loadData();
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
    }
    function clearTextBox() {
        $('#emplyee_id').val("");
        $('#employee_name').val("");
        $('#email_id').val("");
        $('#mobile_no').val("");
        $('#joining_date').val("");
        $('#address').val("");
        $('#is_active').val("");
        $('#btnUpdate').hide();
        $('#btnAdd').show();
        $('#employee_name').css('border-color', 'lightgrey');
        $('#email_id').css('border-color', 'lightgrey');
        $('#mobile_no').css('border-color', 'lightgrey');
        $('#joining_date').css('border-color', 'lightgrey');
        $('#address').css('border-color', 'lightgrey');
        $('#is_active').css('border-color', 'lightgrey');
    }
    function validate() {
        var isValid = true;
        if ($('#employee_name').val().trim() == "") {
            $('#employee_name').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#employee_name').css('border-color', 'lightgrey');
            isValid = true;
        }
        if ($('#email_id').val().trim() == "") {
            $('#email_id').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#email_id').css('border-color', 'lightgrey');
            isValid = true;
        }
        if ($('#mobile_no').val().trim() == "") {
            $('#mobile_no').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#mobile_no').css('border-color', 'lightgrey');
            isValid = true;
        }
        if ($('#joining_date').val().trim() == "") {
            $('#joining_date').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#joining_date').css('border-color', 'lightgrey');
            isValid = true;
        }
        if ($('#address').val().trim() == "") {
            $('#address').css('border-color', 'Red');
            isValid = false;
        }
        else {
            $('#address').css('border-color', 'lightgrey');
            isValid = true;
        }
        return isValid;
    }
</script>


OUTPUT:

Click on the add button and fill the required fields

After submit record list will show

Click on edit for update records

click on delete for delete records

record deleted successfully


Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you for sharing this informative post. Looking forward to read more.
    Web Development Services Delhi/NCR

    ReplyDelete

Post a Comment

Popular posts from this blog

Crud Operation Using DataTable in ASP .Net MVC

How to Add jQuery Datepicker in MVC