Beruflich Dokumente
Kultur Dokumente
com/Articles/609442/Using-JqGrid-in-ASP-Net
home articles quick answers discussions features community help Search for articles, questions, tips
Article
Using JqGrid in ASP.Net About Article
Browse Code
By K K Kodoth, 22 Jun 2013
Stats ow to integrate JqGrid in
5.00 (16 votes) ASP.net
Revisions (7)
Type Article
Alternatives
Download demo - 347.8 KB Licence CPOL
Comments & Download demo - 1.3 MB First Posted 20 Jun 2013
Discussions (33)
Views 4,552
The reason for me to put up an article on this is due to the fact that I couldn't find any resources on the net that
outlines the JqGrid integration end to end. Top News
As number of users increase, the search result also started growing enormously, we started getting more
Related Videos
than 300 search results with the same combination.
This made the user really difficult to find the exact person or user. The solution suggested was to provide one more
filtering or searching feature in the client side. The next question aroused here is how we can add these features for
the existing grid or is there any control which provides the feature available in market.
This search took us to JqGrid which is a free control which has got all the above mentioned features, which can be
done with very less coding effort
1 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
For your better understanding, I have created a demo application called JQGridDemo to show the Integration and jqGrid MVC Html Helper
features. ASP.NET MVC HTML Helper for
the jqGrid
The main thing what we want is the JQuery file, because our hero relays on JavaScript and JQuery.
jqGrid Implementation using
SpServices in SharePoint
Only for the purpose of saving files related to JqGrid Ive created a folder in our solution called JQGridReq.
As a first step I added the JQuery file in to it. An Example to Use jQuery Grid
Plugin in MVC - Part 1
Added JQuery 1.9 to it .I think 1.9 JQuery is the latest stabilized version of JQuery. JqGrid Inline Editing
And what we require next, if we are using any UI related stuffs of JQuery?
MVC Basic Site: Step 3
Yes Of course its' the CSS file. But I searched inside the folder for the JQuery CSS file, I couldn't find that. No Dynamic Layouts and Site
Issues Ok lets do one thing browse and down load from the Internet. Admin with: AJAX, jqGrid,
Controller Extensions, HTML
Better right? Helpers, and more
MVC JavaScript Injection
Ok at last I found from internet. Jquery-ui-1.9.2.custom.css, lets go and add this also to our application. Make sure
that you also add the corresponding image folder also, because we are adding the CSS that might also require the jqGrid Quick Tips
images related to the CSS. MVC Basic Site: Step 1
Multilingual Site Skeleton
So we are now ready with JQuery stuff.
MVC Basic Site: Step 2 -
Exceptions Management
Lets start adding our JqGrid files one by one Sorting Table Columns with
jQuery
1. jquery.jqGrid-4.5.2\src\ jquery.jqGrid.js JavaScript Filtering with JSON
2. jquery.jqGrid-4.5.2\js\i18n\ grid.locale-en.js and Filter Management
3. jquery.jqGrid-4.5.2\css\ ui.jqgrid.css Generating JSON Web Services
from an Existing Database with
Did you notice the second file? which is very important one . CodeFluent Entities
Also we have added css files too.
We are done with prerequisites now.
You can see the files which we have added and their folder structure in the below snap shot.
Related Research
Choosing the Right Charting
Component for Your Enterprise
Product
Ok now what I did is, I went right a way to our page in which we are planning to place the JqGrid.
Here it is Default.aspx page.
Placed an HTML table inside that page with ID jQGridDemo. (This grid is going to act as our hero the JqGrid)
2 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
We have to initialize the table as JqGrid with the fields which we are planning to display in the Grid.
Here I like to display,
1. Id
2. First Name
3. Last Name
4. Last 4 SSN
5. Department
6. Age
7. Salary
8. Marital Status
9. Address.
You can use the below script to initialize the table as grid.
<scripttype="text/javascript">
jQuery("#jQGridDemo").jqGrid({
url:'',
datatype:"json",
colNames:['Id','FirstName','LastName','Last4SSN','Department','Age','Salary',
"Address",'MaritalStatus'],
colModel:[
{name:'_id',index:'_id',width:20,stype:'text'},
{name:'FirstName',index:'FirstName',width:150},
{name:'LastName',index:'LastName',width:150},
{name:'LastSSN',index:'LastSSN',width:100},
{name:'Department',index:'Department',width:80,align:"right"},
{name:'Age',index:'Salary',width:80,align:"right"},
{name:'Salary',index:'Salary',width:80,align:"right"},
{name:'Address',index:'Address',width:150,sortable:false},
{name:'MaritalStatus',index:'MaritalStatus',width:100,sortable:false}
],
rowNum:10,
sortname:'id',
viewrecords:true,
sortorder:"desc",
caption:"ListEmployeeDetails"
});
</script>
3 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
I think after the Grid got displayed, you can read out what I have written while initializing the grid with script right?
The colNames are the header of the Grid.The colModel property is a JSON object data field that is used to configure
each column of the grid.
I can say its the data model to be displayed in the grid like what we use in data set field name.colNames property
should match up with the items in the colModel property.You might be noticed that the url property is left blank.
Why?And also you might be thought that why data is not displayed in the grid right?For both the question I can give
you one single answer.Thats for AJAX callback.
Here for ease of use am using Mongo Db as my Back end.The Next Question arouses here is how the url serves the
purpose of data?
What I have done is, I created Custom Http handler, and the function inside the http handler will fetch the employee
records and writes in the HTTP Response.
The HTTP response would be a JSON string in the above mentioned format.Our JqGrid reads the JSON response and
display in the JqGrid with the help of colMode mentioned before.One thing you have to make note is, we are working
with JSON objects now.JqGrid works with XML data, JSON data and also with Array here we uses JSON.As I mentioned
I have created an .ashx handler called JQGridHandler.ashx.And provided the url of the handler as
http://localhost:58404/JQGridHandler.ashx.I am here going to show you how the data is being red from the handler
which is passing from the grid, by simply calling the URL.As usual if we are passing any data to the handler and to
read it from the Handler, in which parameter we look in to?Yes we will definitely first go and look in to the
context.Request right?Here also we are going to search whether any data is passed in the context request inside Form
parameter.
By looking at the de-bugger and the watch I have kept, you can see that I am looking for something called oper inside
by calling forms.Get(oper); and I hope you also noticed that the Form{}(its an array)property in empty here.
Then how come I get the oper? Yes so the grid data operation depends on the oper param.Going forward Ill show
you what all data could come in oper.So here I am inferring that if oper==null its a grid first time load.Dont get
confused.
Ill make you understand within few sec.Here I am using MONGO db as my data store.
You can see the data fetching code inside the if statement.I hope till here every thing is clear .
Any way I am not going in depth of the handlers, JSON ,Mongo and all, you can use any data base.
Only the connection and data fetching mechanism will vary .
I used mongo because its very simple to use .Ok now we are done with all required plumbing for JqGrid lets see
whether it works or not.
Run It..........
4 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Come lets go and have a party. Can you believe that the table jQGridDemo is behaving like this?
Yea thats it, Thats JqGrid....So now you might be thinking that whats special in this grid... As a simple grid view
only...Did you noticed the storable symbol came on the column header First Name?Did we write code for that?Yea...
Thats the beauty of the grid.Not only for FirstName but for every column on clicking in the column you will get the
sorting button on top column header.
(Here in the example the address filed is not sortable) This is only a sample .
Going forward you can see exiting features like this.Tight your seat belts...
Are you ready to add one more div on bottom of the JqGrid table (jQGridDemo)?Ill show you the magic.Go and add
it...
<tableid="jQGridDemo">
</table>
<divid="jQGridDemoPager">
</div>
Yes, I have added one div on bottom of the div called jQGridDemoPager. Some changes in the script as below.
The pagination bar with Refresh and Search option came up.
5 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Lets go and try search.Did you notice the bottom Search button?Next to Search, a Refresh button too.
But its label is not displayed there right?
There inside the file a section called nav you can see in the above image,
In that you can see refreshtext.Initially that would be blank add the text which you require.
Here I added Refresh as label text .
6 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
you expected.
For me it worked fine.
What about you guys? :)I hope till here almost clear right?My next intention is to make the grid responsive.How can
we edit the grid?Do you think that this also can be done without much effort?Ok lets see.
JqGrid Edit/Add/Delete:
Here in JqGrid all the events and properties are configurable.
Its very simple to do but be careful.Even a small change may make your grid not work as you expected.
To provide your grid with above mentioned functionality, you have to add the below mentioned code in the exact
same order as i mentioned below.
$('#jQGridDemo').jqGrid('navGrid','#jQGridDemoPager',
{
edit:true,
add:true,
del:true,
search:true,
searchtext:"Search",
addtext:"Add",
edittext:"Edit",
deltext:"Delete"
},
{//EDITEVENTSANDPROPERTIESGOESHERE},
{//ADDEVENTSANDPROPERTIESGOESHERE},
{//DELETEEVENTSANDPROPERTIESGOESHERE},
{//SEARCHEVENTSANDPROPERTIESGOESHERE}
);
There is a mantra for the order in which I mention events and properties.
Inside the first curly brackets you have added some parameter as true.
See below image
That means in the grids navigation bar (bottom bar) all the mentioned buttons will display with respective text
mentioned as below.
For better understanding I have marked with same colors.This portion you have to declare explicitly after the JqGrid
initialization events and parameters.
Lets go and have a look at the grid, what all changes had happened.
Please see the highlighted region. You can see all the buttons got displayed,which you set to true in above code
segment.Lets go and add a record.
Click on the Small + Add sign on bottom navigation bar. Small window will pop out like below screen shot.
7 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Fill this out and Click the save button. What will happen? Nothing will happen :). Because you didnt configure any
thing for edit operation.
To perform Edit/Delete and Add operation you have to set one more url property also in the grid i.e. the editurl. This
will call the .ashx handler to perform the Add operation.
You can see image 7 to locate Captions' position. Fill the form then click save .
Lets see what happens...
I kept a debugger in the handler to check whether the save reaches in the handler.
I know that you would be wondering, how the data from UI will reach the handler to insert in to the db.
Yea... As expected the debugger got caught in the handler on clicking the Save button.
Can you see whats there in the form (context.Request.Form)? Yes exactly what we wanted.
The data to be inserted as key value pair. Did you noticed the oper=add now.
So I hope you got a bit idea about oper now than before, when I explained on loading data to grid.
And also the Key of the Key value pair would be the key specified in the grid like FirstName, LastName, Age etc.
So as the value of oper the code inside the add if condition will execute to add the record to DB.
How you read the value from Form? Its very simple
stringstrFirstName=forms.Get("FirstName").ToString();
Like above, you can read any value from the form property of the HTTP request ,replace FirstName with what you
wanted .
After add is successful the handler will write a success string to the HTTP response.
That string will write in the Add/Edit popup over the grid as below .
You might be thinking which event in the client side will receive the response
from the server side after Insert right?
8 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
CompleteScript
******************************************************
$('#jQGridDemo').jqGrid('navGrid','#jQGridDemoPager',
{
edit:true,
add:true,
del:true,
search:true,
searchtext:"Search",
addtext:"Add",
edittext:"Edit",
deltext:"Delete"
},
{//EDITportion
//Canalsosetthewidthandheightoftheeditingwindowasbelowcommentedway
//height:300,
//width:400,
//top:50,
//left:100,
//dataheight:280,
closeOnEscape:true,//Closesthepopuponpressingescapekey
reloadAfterSubmit:true,
drag:true,
afterSubmit:function(response,postdata){
if(response.responseText==""){
$(this).jqGrid('setGridParam',{datatype:'json'
}).trigger('reloadGrid');//Reloadsthegridafteredit
return[true,'']
}
else{
$(this).jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
//Reloadsthegridafteredit
return[false,response.responseText]//Capturesanddisplaystheresponse
textonthEditwindow
}
},
editData:{
EmpId:function(){
varsel_id=$('#jQGridDemo').jqGrid('getGridParam','selrow');
varvalue=$('#jQGridDemo').jqGrid('getCell',sel_id,'_id');
returnvalue;
}
}
},
{//ADDportion
closeAfterAdd:true,//Closestheaddwindowafteradd
afterSubmit:function(response,postdata){
if(response.responseText==""){
$(this).jqGrid('setGridParam',{datatype:'json'
}).trigger('reloadGrid')//ReloadsthegridafterAdd
return[true,'']
}
else{
$(this).jqGrid('setGridParam',{datatype:'json'
}).trigger('reloadGrid')//ReloadsthegridafterAdd
return[false,response.responseText]
}
}
},
{//DELETE
closeOnEscape:true,
closeAfterDelete:true,
reloadAfterSubmit:true,
closeOnEscape:true,
drag:true,
afterSubmit:function(response,postdata){
if(response.responseText==""){
$("#jQGridDemo").trigger("reloadGrid",[{current:true}]);
return[false,response.responseText]
}
else{
$(this).jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid')
return[true,response.responseText]
}
},
delData:{
EmpId:function(){
varsel_id=$('#jQGridDemo').jqGrid('getGridParam','selrow');
varvalue=$('#jQGridDemo').jqGrid('getCell',sel_id,'_id');
returnvalue;
}
}
},
{//SEARCH
closeOnEscape:true
}
);
The above code itself is self descriptive. I have included the code for edit and delete in the above snippet.
One Important thing I would like to say is about Editing. While performing Edit operation, we always update the data
based on some primary key right? Here the primary Key is _id. (_id is employeeid)
While editing or updating, only the data from the Field marked as editable will be transferred to the Handler.
No additional data will be transferred.
If you look at the edit window there the _id is not displayed or marked as editable (with out adding edit parameter by
default all fields are editable) and hence it will not be transferred to the handler in the context.request.Form.
To pass that _id (ie. the employeeid) to the server from our JqGrid, I have used editData property of the JqGrid. We
can use JqGrid delData property to pass the _id for deleting a record.
9 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Note:-Not only for _id you can pass any additional data to handler with the help of editData,delData in JSON format
varsel_id=$('#jQGridDemo').jqGrid('getGridParam','selrow');//GetstheIdofselectedrow
varvalue=$('#jQGridDemo').jqGrid('getCell',sel_id,'_id');//Getsthevalueofcolumnof
selectedrow.(_idisthena,eofthecolumn).
*******************************************************
CodeinHTTPhandler
*******************************************************
publicclassJQGridHandler:IHttpHandler
{
publicvoidProcessRequest(HttpContextcontext)
{
System.Collections.Specialized.NameValueCollectionforms=context.Request.Form;
stringstrOperation=forms.Get("oper");
MONGOConnectobjMC=newMONGOConnect();//HelperClass
varcollectionEmployee=objMC.GetMongoCollection("EMPLOYEE");//GetsEmployeeCollection
stringstrResponse=string.Empty;
if(strOperation==null)
{
//oper=nullwhichmeansitsfirstload.
varjsonSerializer=newJavaScriptSerializer();
context.Response.Write(jsonSerializer.Serialize(collectionEmployee.AsQueryable<Employee>
().ToList<Employee>()));
}
elseif(strOperation=="del")
{
varquery=Query.EQ("_id",forms.Get("EmpId").ToString());
collectionEmployee.Remove(query);
strResponse="Employeerecordsuccessfullyremoved";
context.Response.Write(strResponse);
}
else
{
stringstrOut=string.Empty;
AddEdit(forms,collectionEmployee,outstrOut);
context.Response.Write(strOut);
}
}
publicboolIsReusable
{
get
{
returnfalse;
}
}
privatevoidAddEdit(NameValueCollectionforms,MongoCollectioncollectionEmployee,outstring
strResponse)
{
stringstrOperation=forms.Get("oper");
stringstrEmpId=string.Empty;
if(strOperation=="add")
{
strEmpId=forms.Get("EmpId").ToString();
}
elseif(strOperation=="edit")
{
varresult=collectionEmployee.AsQueryable<Employee>().Select(c=>c._id).Max();
strEmpId=(Convert.ToInt32(result)+1).ToString();
}
stringstrFirstName=forms.Get("FirstName").ToString();
stringstrLastName=forms.Get("LastName").ToString();
stringstrLastSSN=forms.Get("LastSSN").ToString();
stringstrDepartment=forms.Get("Department").ToString();
stringstrAge=forms.Get("Age").ToString();
stringstrSalary=forms.Get("Salary").ToString();
stringstrAddress=forms.Get("Address").ToString();
stringstrMaritalStatus=forms.Get("MaritalStatus").ToString();
EmployeeobjEmp=newEmployee();
objEmp._id=strEmpId;
objEmp.FirstName=strFirstName;
objEmp.LastName=strLastName;
objEmp.LastSSN=strLastSSN;
objEmp.Department=strDepartment;
objEmp.Age=Convert.ToInt32(strAge);
objEmp.Address=strAddress;
objEmp.MaritalStatus=strMaritalStatus;
objEmp.Salary=strSalary;
collectionEmployee.Save(objEmp);
strResponse="Employeerecordsuccessfullyupdated";
}
}
As per the value in strOperation(forms.Get("oper")) null,add,edit and del will carry out the operations from handler and
send custom response back.
Thats all.
10 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Conclusion:
JqGrid is very stylish and simple to integrate grid with lots of amazing functionality.
If somebody ask you to build an application with all these search, sort, filter options with in no time you can very
much go for JqGrid.
And also a suggestion from my side is using Mongo DB for rapid application development is very use full.
For this demo application I have used MONGO as back end DB so I could able to do this with in no time.
If you use our grid view and SQL server for development how many hours will it take to develop an application with all
these features?
Its considerably low to develop using JqGrid and even more if you use MONGO.
I am not promoting mongo, but this I wrote from my experience.
There are many more functionalities to be explored in this JqGrid, thats why in introduction I mentioned its a Tip of
Iceberg.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
K K Kodoth
Software Developer (Senior)
India
11 di 12 24/06/2013 11:10
Using JqGrid in ASP.Net - CodeProject http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-Net
Profile popups Spacing Relaxed Noise Medium Layout Normal Per page 25 Update
Last Visit: 17-Jun-13 8:40 Last Update: 24-Jun-13 6:08 Refresh 1 2 Next
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Mobile Layout: fixed | fluid Article Copyright 2013 by K K Kodoth
Web02 | 2.6.130623.1 | Last Updated 21 Jun 2013 Everything else Copyright CodeProject, 1999-2013
Terms of Use
12 di 12 24/06/2013 11:10