Crud Operation Using DataTable in ASP .Net MVC

Introduction

Here I am explaining  Crud operation using DataTable in Asp.net MVC Application. Datatable is a  plug-in for the jQuery Javascript library, it enhances our table by adding sorting, paging, and filtering abilities to plain HTML tables with minimal effort.

So follow the procedure to add the Datatable in our MVC application

Step 1:Create an MVC Application

Step 2: Select an Empty project template and select MVC from add folder and code reference



Step 3: Use Database first approach to update Edmx and setup connection for more please follow this link  https://kmapwm.blogspot.com/2020/09/mvc-datepicker.html

Step 4: Now we need to add the reference By default, Visual Studio will not add a reference for us. For this Browse JQuery.UI.combined, Update Jquery, Bootstrap.datepicker,Jquery.datatables.net, FontAwesome  and toastr in Manage nugget package. 


Controller:

  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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using CrudOperationUsingDatatable.Models;

namespace CrudOperationUsingDatatable.Controllers
{
    public class Result
    {
        public Result()
        {
            this.MessageType = MessageType.Success;
        }
        public string Message { get; set; }
        public MessageType MessageType { get; set; }
    }
    public enum MessageType
    {
        Success,
        Error,
        Info,
        Warning,
        InvalidPassword
    }
    public class EmployeeController : Controller
    {
        dbEntities db = new dbEntities();
        Result result = new Result();
        // GET: Employee
        public ActionResult Index(string id)
        {
            employee e = new employee();
            if (id != null && id != "")
            {
                e = db.employees.Find(Convert.ToInt32(id));
            }
            return View(e);
        }

        public ActionResult List()
        {
            var list = db.employees.AsEnumerable().ToList();
            var data = (from li in list
                        select new
                        {
                            emplyee_id= li.emplyee_id,
                            employee_name = li.employee_name,
                            email_id = li.email_id,
                            mobile_no = li.mobile_no,
                            joining_date = li.joining_date.ToString("dd/MM/yyyy"),
                            address = li.address,
                            is_active = li.is_active
                        }).ToList();
            return Json(data);
        }
        // GET: /Employee/Edit
        public ActionResult Edit(string id)
        {
            var data = (from li in db.employees.AsEnumerable()
                        where li.emplyee_id == Convert.ToInt32(id)
                        select new
                        {
                            emplyee_id=li.emplyee_id,
                            employee_name = li.employee_name,
                            email_id = li.email_id,
                            mobile_no = li.mobile_no,
                            joining_date = li.joining_date.ToString("dd/MM/yyyy"),
                            address = li.address,
                            is_active = li.is_active
                        }).FirstOrDefault();
            return Json(data,JsonRequestBehavior.AllowGet);
        }
        // POST: /Employee/CreateEdit
        [HttpPost]
        public ActionResult CreateEdit(employee empobj)
        {           

            try
            {
                if (empobj.emplyee_id > 0)
                {
                    employee tempempobj = db.employees.Find(empobj.emplyee_id);
                    tempempobj.employee_name = empobj.employee_name;
                    tempempobj.email_id = empobj.email_id;
                    tempempobj.joining_date = empobj.joining_date;
                    tempempobj.mobile_no = empobj.mobile_no;
                    tempempobj.is_active = empobj.is_active;
                    db.Entry(tempempobj).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    result.MessageType = MessageType.Success;
                    result.Message = string.Format("Employee Details Update Sucessfully");

                }
                else
                {
                    empobj.is_active = true;
                    db.employees.Add(empobj);
                    db.SaveChanges();
                    result.MessageType = MessageType.Success;
                    result.Message = string.Format("Employee Created Successfully");
                }
            }
            catch (Exception ex)
            {
                result.MessageType = MessageType.Error;
                result.Message = ex.Message;
            }
            ViewBag.Title = empobj == null ? "Employee Create" : "Employee Edit";
            return Json(result);
        }
        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);
        }

    }
}
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@model CrudOperationUsingDatatable.Models.employee

<style>
    .page-title {
        color: #1f1f1f;
        font-size: 22px;
        font-weight: 500;
        margin-bottom: 5px;
    }

    .page-header {
        margin-bottom: 0.875rem;
    }

    .toast {
        opacity: 1 !important;
    }
</style>

<div class="container">
    <h2>Employee 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="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-0">List</h4>
            </div>
            <div class="card-body">
                <div class="table-responsive m-t-40">
                    <table id="example" class="table table-bordered table-striped dataTable no-footer" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Sr.</th>
                                <th>Employee</th>
                                <th>Mobile no</th>
                                <th>Email ID</th>
                                <th>Joining Date</th>
                                <th>Address</th>
                                <th>Active</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>

    </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">

                @using (Html.BeginForm("CreateEdit", "Employee", FormMethod.Post, new { id = "frmEmployee", @class = "form-material m-t-40" }))
                {
                    @Html.AntiForgeryToken()
                    @Html.HiddenFor(m => m.emplyee_id)

                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Emoployee <span style="color:red">*</span></label>
                                @Html.TextBoxFor(m => m.employee_name, new { @class = "form-control form-control-line", id = "employee_name", placeholder = "Employee", required = "required", title = "Employee" })
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Mobile no<span style="color:red">*</span></label>
                                @Html.TextBoxFor(m => m.mobile_no, new { @class = "form-control form-control-line", id = "mobile_no", placeholder = "mobile_no", required = "required", title = "mobile_no" })
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Email ID <span style="color:red">*</span></label>
                                @Html.TextBoxFor(m => m.email_id, new { @class = "form-control form-control-line", id = "email_id", placeholder = "email_id", required = "required", title = "email_id" })
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Joining Date <span style="color:red">*</span></label>
                                @Html.TextBoxFor(m => m.joining_date, new { @class = "form-control form-control-line datepicker", id = "joining_date", placeholder = "joining_date", required = "required", title = "joining_date" })
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <label>Address <span style="color:red">*</span></label>
                                @Html.TextBoxFor(m => m.address, new { @class = "form-control form-control-line", id = "address", placeholder = "address", required = "required", title = "address" })
                            </div>
                        </div>
                        <div id="DivIsActive" style="display:none">
                            <div class="col-md-12">
                                <div class="form-group ">
                                    <label>Enable</label>
                                    <input type="checkbox" style="height: 15px;width: 15px;" class=" form-control" name="is_active" id="is_active" checked="checked">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>

                    <button type="button" id="btnAdd" onclick="btnSave()" class="btn waves-effect waves-light btn-primary">Submit</button>
                    <button type="button" id="btnUpdate" onclick="Update()" class="btn waves-effect waves-light btn-primary">Update</button>
                    <button class="btn waves-effect waves-light btn-secondary" onclick="Cancel()" data-dismiss="modal" data-toggle="quickview" aria-hidden="true">cancel</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.dataTables.min.js"></script>
<link href="~/Content/font-awesome.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/toastr.min.js"></script>
<link href="~/Content/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="~/Content/toastr.min.css" rel="stylesheet" />


<script>
    $(document).ready(function () {
        $('#btnUpdate').hide();
        $('#DivIsActive').hide();
        $(".datepicker").datepicker({ dateFormat: "dd/mm/yy", changeMonth: true, changeYear: true, buttonText: "Select", showOn: 'both' }).val()
        BindDataTable();
    });
     function BindDataTable() {
            var table = $('#example').DataTable();
            var i = 1;
            table.destroy();
            $('#example').DataTable({
            "ordering": false,
                dom: 'lBfrtip',
                buttons: ['csv','copy','excel','print'],
                "ajax": {
                    type: "POST",
                    url: '@Url.Action("List", "Employee")',
                    datatype: "json",
                    data: { id: "0" },
                    dataSrc: ""
                },
                columns: [
                    {
                        "render": function (data, type, full, meta) {return i++;}
                    },
                    { data: "employee_name", name: "employee_name", autoWidth: true },
                    { data: "email_id", name: "email_id", autoWidth: true },
                    { data: "mobile_no", name: "mobile_no", autoWidth: true },
                    { data: "joining_date", name: "joining_date", autoWidth: true },
                    { data: "address", name: "address", autoWidth: true },
                    {
                        data: "is_active",
                        "render": function (value) {
                            return value ? "<span class='label label-success'>Enable</span>" : "<span class='label label-danger'>Disable</span>"
                        }
                    },

                    {
                        data: "emplyee_id",
                        "render": function (data, type, row) {
                            return "<div class='action-btn '><a style='cursor:pointer' onclick='getbyID(" + row.emplyee_id + ")' ><i class='fa fa-pencil'></i></a>|<a style='cursor:pointer' onclick='Delete(" + row.emplyee_id + ")' ><i class='fa fa-trash'></i></a></div> "
                        }
                    },
                ],
            });
      $(".dt-buttons").css('display', 'none');
        }
    function btnSave() {
        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/CreateEdit",
                type: "POST",
                data: empObj,
                success: function (result) {
                    if (result.MessageType == 0) {
                        toastr.success(result.Message);
                        toastr.options.timeOut = 300;
                    }
                    else {
                        toastr.error(result.Message);
                        toastr.options.timeOut = 300;

                    }
                    $('#myModal').modal('toggle');
                    BindDataTable();

                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
            clearTextBox();
        }
        else {
            return false;
        }
    };
    function getbyID(Id) {
        $('#emplyee_id').val(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/Edit/" + Id,
            typr: "GET",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (data) {
                $('#employee_name').val(data.employee_name);
                $('#email_id').val(data.email_id);
                $('#mobile_no').val(data.mobile_no);
                $('#joining_date').val(data.joining_date);
                $('#address').val(data.address);
                if (data.is_active == true) { $('#is_active').prop('checked', true); } else { $('#is_active').prop('checked', false); }
                $('#myModal').modal('show');
                $('#DivIsActive').show();
                $('#btnUpdate').show();
                $('#btnAdd').hide();

            },
            error: function (errormessage) {
                alert("error");
                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/CreateEdit",
                data: JSON.stringify(empObj),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    if (result.MessageType == 0) {
                        toastr.success(result.Message);
                        toastr.options.timeOut = 300;
                    }
                    else {
                        toastr.error(result.Message);
                        toastr.options.timeOut = 300;

                    }
                    $('#myModal').modal('hide');
                    clearTextBox()
                    BindDataTable();

                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
            clearTextBox();
        }
    }
    function Delete(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) {
                    BindDataTable();
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
    }
    function Cancel() {
        $('#btnUpdate').hide();
    }
    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>

Step5 : Add controller and view to our MVC Application 




Step 6  Here Is the Crud Operation using DataTable in Asp.net MVC Run the code we will get the Datatables as in the following:

Crud operation using Datatable in Asp.net MVC



Summary

In this example, we have discussed How to add a Datatabel in  MVC  or implement Datatabel to MVC. Copy the sample code for a better understanding. Thanks. I would like to get feedback from my readers. Please post your feedback, question, or comments about this article
















Comments

Post a Comment

Popular posts from this blog

Crud operation using Ajax in ASP.NET MVC

How to Add jQuery Datepicker in MVC