Jqgrid
Jqgrid
Jqgrid
TodoList is a simple web application to create, store and modify Todo tasks to be maintained
by the users, which comprises of following fields to the user (Task Name, Task Description, Severity,
Target Date, Task Status).
TodoList web application is created using MVC - 4 architecture, code-first Entity Framework
(ORM) and Jqgrid for displaying the data.
I am dividing this topic in to 2 sections.
Section 1: contains basic theoretical details of the technologies that we are used and the advantages
of using ASP.net MVC-4, Code first Entity Framework and JQgrid technologies.
Section 2: contains the practical implementation of step by step creating a simple TodoList
application using ASP.net MVC-4, Code first Entity Framework and JQgrid.
http://www.codeproject.com/Tips/825724/Section-JQGrid-and-MVC-Demo-with-Custom-Filters-or
---------------------------------------------------------------------------------------------------------------
--------------
Section 1:
MVC
MVC is a pattern for developing applications that are well architected and easy to maintain.
So using MVC we can develop testable, flexible, scalable, extensible standard based applications.
MVC is not a replacement of Asp.net web forms based development. This sits on top of Asp.
net development. MVC framework is defined in "System.Web.MVC.Assembly".
MVC works on Conventions over configurations.
Model
Model represents the application data domain. It can contain a logic related to data
domain.In short the application business logic is contained with in the model.
Model contains a pieces of C# classes with set of properties and validations defined on top
of it using data annotations. It can also contain data access, data aggregation logic etc.
Model can be entities or business logic.
View
Controller
Controller handles the user interaction with the web application.
User requests comes through the controller to model and manipulates the records from it
and render the data using view to UI.
Controller contains the control flow logic.
Controller contains the set of action methods.
Entity Framework
The Microsoft ADO.Net Entity Framework is an Object Relational Mapping (ORM) framework
that enables developers to work with relational data as a domain specific object, eliminating the use
of most of the data access plumbing code that developers usually need to write.
Code First is mainly used in Domain Driven Design(DDD) approach. We can focus on the domain
design and start writing the classes as per the domain requirement rather than design the database
first and then you create the classes that matches your database design. Code first API's will create
the database on the fly based on your entity classes and configuration.
Basically in the real world scenarios there are 2 types of groups or models will be present like Logical
Data Model and Object Oriented Domain Model
Almost any business application today as to speak to a relational database. These relational database
can also say it has a Backend SQLSERVER contains all the Stored Procedures, tables with foreign key,
view etc. Which will be handled by 1 group of people called as database centric.
Object Oriented Domain Model
Applications are developed completely different from the logical data model. These Object Oriented
Domain Model deals with objects, behaviors, properties, inheritance, polymorphic etc. Which will be
handled by 1 group of people called as application centric.
Impedence Mismatch
As a result of above 2 models impedance mismatch occurs, as the developers devote a lot of time
and energy writing code to translate between how the database likes to see the data and how the
application likes to see the data.
So Ado .net Entity Framework seeks to remedy to problem by providing the layer of
abstraction between the logical data model and the application domain model.
JQGRID
Jqgrid is an ajax enabled javascript control that provides solution for representing and manipulation
tabular data on the grid. Since grid is a client side solution loading data dynamically through ajax call
backs, it can be integrated with any server side technology, including php, ASP java servelets, JSP and
perl.
JQGrid uses Jquery javascript library.
Requirements
JQGrid plugin
Jquery library, version 1.1.4 or above.
web browser
data can be stored in xml, json
a web server (IIS, Apche, Tomcat)
a db backend (SQL Server, Oracle MSSql )
a server side scripting language( PHP, ASP)
JQGrid is a component that helps you in an easy way to represent database information on the client
side using a server side technology. Moreover that helps you to manipulate data back in to database.
Features of JQGrid
JQGrid helps us to develop most browser compatibility web pages and also supports cross
browser support functionality.
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.
Pagination functionality is present. So no need to retrieve all the data from the server.
Sorting, Various data types and sub grid support functionality.
Event handlers and User API.
Formatter supports advanced formating of the contents of the cell in the required format in
the client side itself.
Inline Editing: easy to update the cell content in a particular row.
Searching and filtering.
Import and Export data.
Section 2:
Creating simple TodoList application using
MVC-4, Code-first Entity Framework and
Jqgrid.
Open a layout page present inViews ->Shared ->_Layout.cs page and add a new Action Link
for TODOLIST tab.
Hide Copy Code
<li>@Html.ActionLink("TodoList", "Index", "TodoList")</li>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
Goto tools -> Library Package Manager -> Package Manger Console.
Install entity framework - 5 in package manager console.
Right Click on References and click on Manage Nuget.
Search for Jqgrid and select JQueryJQGrid and install it.
Add a TodoList class file in the Model for storing entities.
Open -> "TodoList.cs" and add the required Entities to the TodoList model class.
Todo List contailns all the properties that are used in the screen.
Hide Copy Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TodoListDemoApplication.Models
{
public class TodoList
{
public int Id { get; set; }
public string TaskName { get; set; }
public string TaskDescription { get; set; }
public DateTime TargetDate { get; set; }
public string Severity { get; set; }
public string TaskStatus { get; set; }
}
}
Created TodoContext acts like a bridge or acts like a connection object between database
and the LinqObject which will be similar to Ado.net connection object.
Add a DbseDbSet represents the tables which will be present in the database.
Hide Copy Code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TodoListDemoApplication.Models;
namespace TodoListDemoApplication.DBContext
{
public class TodoContext:DbContext
{
public DbSet<TodoList> TodoLists { get; set; }
}
Modify the Connection String in the web.config file and the name will be Context Name
(TodoContext) which we have created it.
Also give the proper conncetion string details like data source, Initial catalog and provider
name etc.
Hide Copy Code
<connectionStrings>
<add name="TodoContext"
connectionString="Data Source=(Local);Initial Catalog=TodoListDemo;Integrated
Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Once after enabling the migrations for the particular context that we are using, next step is to
Add Migration.
Execute "Add-Migration" command in package mangaer console. This will generate
Migration file, sql code and this will not be executed in SQL Server unless and untill we run "update-
database" command.
Open the Sql Server and check the database and the table which got automatically
generated using code migration Entity framework approach.
Add a Todolist Controller.
Add a view to index action method.
@{
ViewBag.Title = "Index";
}
<style>
.ui-jqgrid .ui-userdata {
height: auto;
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/TodoList.js"></script>
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
JQGrid functionality code is added in a TodoList.js file which will be placed inside the Jquery
ready function
Few important JQGrid property details that normally used with explanation.
Add the required Jquery, Jqgrid script reference in the index page in the following order.
Remove the jquery reference in the layout file to avoid the conflict.
Run the application, we will should be able to see the Jqgrid.
Next step is to implement CRUD functionality in JQGrid.
Add navGrid functionality with CRUD operations implemented in JQGrid present in
"TodoList.Js" file.
----------------------------source code of TodoList.js
$(function () {
debugger;
$("#grid").jqGrid({
url: "/TodoList/GetTodoList",
datatype: 'json',
mtype: 'Get',
//table header name
colNames: ['Id', 'Task Name', 'Task Description', 'Target Date', 'Severity','Task
Status'],
//colModel takes the data from controller and binds to grid
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'TaskName', index: 'TaskName', editable: true },
{ key: false, name: 'TaskDescription', index: 'TaskDescription', editable:
true },
{ key: false, name: 'TargetDate', index: 'TargetDate', editable: true,
formatter: 'date', formatoptions: { newformat: 'd/m/Y' } },
{ key: false, name: 'Severity', index: 'Severity', editable: true, edittype:
'select', editoptions: { value: {'L':'Low','M':'Medium','H':'High'}} },
{ key: false, name: 'TaskStatus', index: 'TaskStatus', editable: true,
edittype: 'select', editoptions: { value: { 'A': 'Active', 'I': 'InActive' } } }],
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: true
//pager-you have to choose here what icons should appear at the bottom
//like edit,create,delete icons
}).navGrid('#pager', { search:true,edit: true, add: true, del: true, search: false,
refresh: true,searchtext:"Search" },
{
// edit options
zIndex: 100,
url: '/TodoList/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/TodoList/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// delete options
zIndex: 100,
url: "/TodoList/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);
}
}
});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false,
searchOperators: true, defaultSearch: "cn" });
});
Create is a HTTP Post action method in TodoList Controller for creating the Todo List.
Entity framework is been used for inserting in to the database avoiding the use of ado.net
mechanism.
Internally Entity frame Work will generate the query and run in the database only after
SaveChanges method is been called.
"ModelState.IsValid" is used to validate the model. "ModelState.IsValid" will return true if all the
model validations are satisfied in the server-side, else returns false and will not allow to execute the
further code.
---------------------plain Source code of above image is
// TODO:insert a new row to the grid logic here
[HttpPost]
public string Create([Bind(Exclude = "Id")] TodoList obj)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.TodoLists.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
1.
2. Edit action method is used to update the edited Todo List row in the JQGrid.
3. Delete action method is used to delete the selected Todo List row in the JQGrid.
---------------------plain Source code of above image is
Lets add 1 task item to the Todo List by clicking on + button present in the Page navigator.
Submit the data after entering the valid data will save the data into the JQGrid.
Editing one of the Todo List in the JQGrid.