CRUD Operations In JTable Using MVC

Introduction

In this article, we will discuss CRUD (Create, Read, Update, Delete) Operations functionality In jTable Using MVC and entity framework. I will use visual studio 2012 framework and SQL server 2008 R2 for this demo.

So, before opening visual studio let's create and populate student table using following script.


Student table scrip

1
2
3
4
5
6
7
8
Create table student
(
StudentId varchar(50),
RollNo varchar(50),
FullName varchar(50),
Gender varchar(10),
City varchar(50),
)

1
2
3
4
5
6
Insert into student values('016a7375-6da4-471b-9182-e1a122828d9e',1,'Sara','Female','Chennai')
Insert into student values('048e49c9-8cb0-4b18-8afe-9c2f89e0ddf1',2,'David','Male','Sydeny')
Insert into student values('04e4d633-f0af-4269-be06-1b4a5588ae0d',3,'Dora','Female','New York')
Insert into student values('071e0c85-50eb-4283-8d7f-1b055990a944',4,'Maya','Female','London')
Insert into student values('0c868ccb-382d-4349-a338-97210a17d254',5,'Vikram', 'Male','Mumbai')
Insert into student values('17f95a81-934d-43fd-b780-4afd8509d8e0',6,'Nikhil','Male','Delhi')

Step 1: Create MVC project, by using following steps.

  1. Open Visual Studio.
  2. Click on File -> New -> Project.
  3. In this project, I am using C# as a programming language, but you can also choose VISUAL BASIC if you know syntaxes of VB.
  4. Inside Visual C# -> Web -> Project -> Select Asp.Net MVC 3, 4 or 5 -> Name your project -> JtableDemo -> Select Ok
  5. Crud Operation
  6. Now one more dialog box will open -> select 'Internet Application' as a project template. -> OK.
  7. Crud Operation

Step 2: Install 'jTable' and 'entity framework' from NuGet Package Manager by using following steps

  1. Open solution explorer -> Right click on your project name and click on Manage Nuget Packages
  2. Crud Operation
  3. Go to online tab and Search for jTable and click on install button.
  4. Crud Operation
  5. Now search for Entity framework and click on install button.
  6. Crud Operation
  7. Once you install jtbale and entity framework. You will find them inside your project folder.
  8. Crud Operation

Step 3 : Add new folder in your project for entities.

  1. Right click on your project name -> click add -> click New Folder -> rename that new folder to 'Entities'
  2. Crud Operation
  3. Once you created 'Entities' folder add one class file inside that folder -> name that class file -> Student.cs
  4. Crud Operation
  5. Copy and paste following code inside student class file.

  6.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    namespace JtableDemo.Entities
    {
        [Table("student")]
        public class Student
        {
            public string StudentId { get; set; }
            public string RollNo { get; set; }
            public string FullName { get; set; }
            public string Gender { get; set; }
            public string City { get; set; }      
        }
    }
    

  7. Now add one more class file inside Entities folder, name that file name -> 'StudentContext' -> Copy following code inside studentcontext class file.
  8. Crud Operation

    StudentContext.cs

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using JtableDemo.Entities;
    
    
    namespace JtableDemo.Models
    {
        public class StudentContext : DbContext
        {
            public DbSet<Student> Students { get; set; }
        }
    }
    

Step 4 : Add new controller using follwing steps


  1. Right click on controller folder. Name your controller -> StudentController -> Click on Add button.
  2. Crud Operation
  3. Now open StudentController and add following 4 methods in your controller.

  4. Index method

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    using JtableDemo.Entities;
    using JtableDemo.Models;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace JtableDemo.Controllers
    {
        public class StudentController : Controller
        {
            //
            // GET: /Student/
    
            public ActionResult Index()
            {
                return View();
            }
        }
    }
    

    GetStudentDetails Action

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
     public JsonResult GetStudentDetails()
            {
                StudentContext db = new StudentContext();
                try
                {
                    List<Student> students = new List<Student>();
                    students = db.Students.ToList();
                    return Json(new { Result = "OK", Records = students }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "ERROR", Message = ex.Message });
                }
            }
    

    Create Action

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
     [HttpPost]
            public JsonResult Create(Student Model)
            {
                StudentContext db = new StudentContext();
                try
                {
                    Model.StudentId = Guid.NewGuid().ToString();
    
                    db.Students.Add(Model);
                    db.SaveChanges();
                    return Json(new { Result = "OK", Records = Model }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "ERROR", Message = ex.Message });
                }
            }
    

    Edit Action

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
      [HttpPost]
            public JsonResult Edit(Student Model)
            {
                StudentContext db = new StudentContext();
                try
                {
                    db.Entry(Model).State = EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "ERROR", Message = ex.Message });
                }
            }
            
    

    Delete Action

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    [HttpPost]
            public JsonResult Delete(String StudentID)
            {
                StudentContext db = new StudentContext();
                try
                {
                    Student students = db.Students.Find(StudentID);
                    db.Students.Remove(students);
                    db.SaveChanges();
                    return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "ERROR", Message = ex.Message });
                }
            }  
    

Step 5 : Add view using following steps.


  1. Open student controller -> Right Click on Index method.
  2. Click on Add View Option.
  3. Crud Operation
  4. Add following code inside your index.cshtml

  5.  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
    @{  
        ViewBag.Title = "Student Details";  
    }  
      
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h2>Student Details</h2>  
      
    <div id="StudentsTable"></div>  
      
    @section scripts{  
        <!--Adding Theme for jTable Grid-->  
        <!--You can choose any type of theme from the themes folder-->  
        <link href="~/Scripts/jtable/themes/metro/blue/jtable.min.css" rel="stylesheet" />  
        @*<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />*@  
        <link href="http://jtable.org/Content/themes/metroblue/jquery-ui.css" rel="stylesheet" type="text/css" />  
    
        
    
        <script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>  
      
        <!--Adding jTable Plugin-->  
        <script src="~/Scripts/jtable/jquery.jtable.min.js"></script>  
      
         
    }  
    <script type="text/javascript">
    
    $(document).ready(function () {
        $('#StudentsTable').jtable({
            title: 'Students Detail',
            actions: {
                listAction: '/Student/GetStudentDetails',
                createAction: '/Student/Create',
                updateAction: '/Student/Edit',
                deleteAction: '/Student/Delete'
            },
            fields: {
                StudentId: {
                    key: true,
                    list: false
                },
                RollNo: {
                    title: 'Roll Number',
                    width: '15%'
                },
               FullName: {
                    title: 'Student Name',
                    width: '45%'
                },
                Gender: {
                    title: 'Gender',
                    width: '15%',
                },
                City: {
                    title: 'City',
                    width: '15%',
                }
               
            }
        });
        $('#StudentsTable').jtable('reload');
    });
        </script>
    

Step 6 : Web.config


  1. Replace your connectionstring with following code inside your web.config file

  2.  1
    2
    3
     <connectionStrings>
        <add name="StudentContext" connectionString="data source=.;initial catalog=Sample;integrated security=True" providerName="System.Data.SqlClient" />
      </connectionStrings>
    

Step 7 : Press F5 and see result


  1. List of students Crud Operation
  2. Add new students Crud Operation
  3. Edit existing record Crud Operation
  4. Delete student record Crud Operation
Download Source Code

Related Topics

Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.