Friday, 1 April 2016

Implementing Jqgrid in ASP.NET MVC

Leave a Comment

Jqgrid in MVC 4:

Introduction:
Hi every one.Thank u for your comments on the previous articles.In this article i am going to tell you how to implement Jqgrid in ASP.NET MVC.

JqGrid: Jqgrid is nothing but a jquery plugin.It is a Ajax enabled javascript control provides solutions for representing and manipulating tabular data on the web.There are many plugins for jquery to display in table manner with the client side controllers.But, The good thing about Jqgrid is it is completely open source plugin we can use it for production without paying single penny.  Actually this plugin is mainly targets the PHP as backend. But, we can use it ASP.NET MVC application also.  There are many other plugins like Jqgrid.
1.Bootstrap grid(latest one)
2.Gurido grid
3.Kendo Grid(closed source application)
etc there are number of plugins among those jqgrid performance is good.

features of Jqgrid:

1.JQGrid helps us to develop most browser compatibility web pages and also supports cross browser      support functionality.
2.CSS based themes. Developers can change the grid skin by defining their own UI CSS framework.
   The new rendering engine is 5-10 times faster loading speed then the previous.
3.Pagination functionality is present. So no need to retrieve all the data from the server.
4.Sorting, Various data types and sub grid support functionality.
5.Event handlers and User API.
4.Formatter supports advanced formating of the contents of the cell in the required format in the
   client side itself.
5.Inline Editing: easy to update the cell content in a particular row.
6.Searching and filtering.
7.we can import and export data 

Implementing Jqgrid:

Step 1: Create Visual studio application
1.open visual studio 2015.
2.create ASP.NET MVC web application.
3.choose MVC template from the predefined templates and click ok.


Step 2: Add Jqgrid resources to the project
1.right click solution-->manage nuget packages-->In "Nuget package manager window" select the Jquery-Jqgrid and click install.


2.now the required jqgrid resources are added to the project.you can see files in solution exporer
3.if there is no Entity framework 5.0.0 in your visual studio install it.
Step 3: prepare data source for Jqgrid
1.right click App_Start-->Add-->New Item-->Selct "Sql Database" from Data templates-->name it as Database.mdf.
2.click Add button then database created.
3.Now Add Create User table: goto server explorer-->expand data connections-->expand DatabaseEntities-->Tables-->Add New Table.


4.click update button-->click Update database on next window.then table created.
5.Model Class creation:
  right click models folder-->Add-->New Item -->ADO.NET Entity Data Model
6.Select Model Components from Database.


7.choose database from dropdown. DataEntities.mdf.and name the connection string below.


8.select table

9.Model classes are created in the .edmx file in Models folder like this..


Step 4: create controller
1.right click Controllers folder-->add-->Controller-->select empty controller template-->name it as JqgridController.
JqgridController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Jqgrid.Controllers
{
    public class JqgridController : Controller
    {
        // GET: Jqgrid
        public ActionResult Index()
        {
            return View();
        }
    }
}

2.now right click Index action method and add view
replace the view code with following code..In this view we are adding the references to the libreary files also.
@{
    ViewBag.Title = "Todo List";
}
<h2>Todo List</h2>
<div>
    <table id="grid"></table>
    <div id="pager"></div>
</div>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/myjqgrid.js"></script>

Step 5: Prepare Json method to send data to Jqgrid.
Now Modify the JqgridController/Index method.

using System;
using System.Data;
using System.Linq;
using System.Data.Entity;
using System.Web.Mvc;
using Jqgrid.Models;
namespace Jqgrid.Controllers
{
    public class JqgridController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        DatabaseEntities1 db = new DatabaseEntities1();
        public JsonResult GetValues(string sidx, string sord, int page, int rows)  //Gets the todo Lists.
        {
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var Results = db.Users.Select(
                    a => new
                    {
                        a.Id,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.DOB,
                    });
            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.Id);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.Id);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        // TODO:insert a new row to the grid logic here
        [HttpPost]
        public string Create([Bind(Exclude = "Id")] User obj)
        {
            string msg;
            try
            {
                if (ModelState.IsValid)
                {
                    db.Users.Add(obj);
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successfull";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }
            return msg;
        }
        public string Edit(User obj)
        {
            string msg;
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(obj).State = EntityState.Modified;
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successfull";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }
            return msg;
        }
        public string Delete(int Id)
        {
            User list = db.Users.Find(Id);
            db.Users.Remove(list);
            db.SaveChanges();
            return "Deleted successfully";
        }
    }
}
2.Using GetValues Json method we are binding the db data to the jqgrid in the format of Json(javascript object notation).
3.here parameters sidx=maens serial index,sord variable for sorting order,page numbers of pages,row parameter takes the numbers rows in jqgrid.
4.Finally we are binding data using json() method as a  json object.

 Step 5: Create script for Jqgrid.
The javascript code format for jqgrid is as follows:
1.Create myjqgrid.js:

$(function () {
    debugger;
    $("#grid").jqGrid({
        url: "/Jqgrid/GetValues",
        datatype: 'json',
        mtype: 'Get',
        //table header name 
        colNames: ['Id', 'Name', 'Phone', 'Address', 'DOB'],
       //colModel takes the data from controller and binds to grid 
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'Name', index: 'Name', editable: true },
            { key: false, name: 'Phone', index: 'Phone', editable: true },
            { key: false, name: 'Address', index: 'Address', editable: true },
            { key: false, name: 'DOB', index: 'DOB', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],
            
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        caption: 'Jq grid sample Application',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        autowidth: true,
        multiselect: false
        //pager-you have to choose here what icons should appear at the bottom
        //like edit,create,delete icons
    }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true },
        {
            // edit options
            zIndex: 100,
            url: '/Jqgrid/Edit',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // add options
            zIndex: 100,
            url: "/Jqgrid/Create",
            closeOnEscape: true,
            closeAfterAdd: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // delete options
            zIndex: 100,
            url: "/Jqgrid/Delete",
            closeOnEscape: true,
            closeAfterDelete: true,
            recreateForm: true,
            msg: "Are you sure you want to delete this task?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });
});

Now run the application:
Note: After running the if you did not get any grid display just go to _Layout.cshtml page which is present in Views/Shared folder .and just comment the
@Scripts.Render("~/bundles/jquery")



And change the route.config

final output of the application is(i inserted some records in the USer table)


Add you can also implement CRUD operations on Data
ADD new record-->if you click the plus button on left below corner then a popup will appear like this


like this you can perform CRUD operations on JQgrid which out postback.Because Jqgrid performs all operations through AJAX only.

Download sample code from here.(opens in visual studio 2015)

Conclusion:
I hope you enjoyed the article.I always welcome for any suggestions from you..


0 comments:

Post a Comment