Introduction
I am writing a new article after long time, and the topic I chose here is JQGrid.
Got very good response for the articles that I have written on JQGrid.
I would like to thank all of my reader friends for supporting me, spent time on my articles and given me valuable feedbacks that fueled me to write a new one.
I've got lots of Questions from my previous articles on JQGrid, but I could not able to respond that questions effectively as required, apologies for the same.
So with this article I also would like to provide answers to those questions, as well.
You might be curious to know about what am I writing here.
Yes…
Here I am trying to show you, how we can use JQGrid in MVC 4 or say in an MVC application.
One question that I got from the readers is how we can use the JQGrid in MVC 4 Application.
It’s similar to what we have done for asp.net application as described in my previous article.
I am planning this as a stage set up for my upcoming articles on JQGrid and MVC.
How are we going to do this
Here am using visual studio 2012 to develop this demo application,with the expectation that you know how to create an MVC 4 application with the basic template.
So we have started setting our stage for the play.
First plan is to make an MVC 4 Application up and running with one single view (Page).
Follow the steps to create a view and make the application up and Running.
Creating a basic MVC 4 Application in VS 2012
Open VS 2012
--> File
--> New Project
--> Web
-->Asp.net MVC 4 Web application
-->Select Template
-->Empty
Then provide a name you like for your project, here I’ve given JQGridJQueryPlugin as my project and solution name …
hope that sounds good.
As a result of the above steps, I could able to create an awesome solution as below with the file structure.
As the next step, we have to create a controller then a view from the controller.
Right click the Controllers folder --> Add -->controller --> DefaultController.
So we created a controller with the name DefaultController.
Next step is to create a View from the controller.
Open DefaultController.cs file --> inside you can see an action method called Index() -->Right click on it and then a context menu will pop up--> from that select Add View --> name the View as Index itself.
So now our Solution would look like below image.
Try to run your application ….
Have you tried…?
Then what happened…?
Yeaa…
I can understand…
The application would throw a 404 exception, because the application would be looking for a Home controller and an Index action by default, that is already set in the Routing configuration .
Anyway am not going indepth of routing, and all to mitigate this exception what you have to do all is, edit RouteConfig.cs file inside App_Start Folder .
Change the controller name inside the MapRoute from Home to Default.
Now try to run your application see what happens …
Yea…
You would be getting a web page with a text Index written on the page, Correct?
If you are getting it a browser like above, we can say that our stage is set.
Let’s go and add a bit style on it to look attractive, anyway am not going to create a new style sheet myself .
Let's google for free css templates and find something interesting.
Ok, after 15 minutes of searching, I found something simple and standard.
Why i put this much effort is only because ,I do not like the applications without a minimum styles applied on it; that’s why I put this much effort to find something better.
You do not worry about the CSS. What you all have to do is Just Download the solution folder and copy the styles folder into your root directory of your solution, and then I’ve created a Folder called as below inside the solution root.
From the above BaseHtml.html file copy the entire content to your Index.cshtml file .
Make sure that the all the contents inside the Index.cshtml file is deleted before pasting the content from BaseHtml.html.
Then try to run your application ….
Looks really beautiful ...
Correct?
Here is mine.
So we are all done with our MVC Application with a single stylish web page.
I can understand that those who are already expert in MVC, definitely you would be cursing me; nothing but for wasting your valuable time .
Apologies to those …
My intention is, even a new developer without MVC experience also can come and try this directly without depending on any other supporting materials.
Plugging JQGrid with MVC Application:
Ok let’s go for it.
First download the latest version of JQGrid from http://www.trirand.com/blog/?page_id=6 click the download button in the bottom of the page, which would download all the required files for the grid as a zip file .When I tried the download, I got the zipped folder with name jquery.jqGrid-4.6.0, which says that I have downloaded the 4.6.0 version of JQGrid.
Then extract the zipped file in a convenient location.
Now we can start adding required files from the extracted folder to our solution one by one.
First create a folder with name Script and inside Scripts add one more folder called JQGrid add the .JS files in the snapshot ,from the location \jquery.jqGrid-4.6.0\js
And also add the file \jquery.jqGrid-4.6.0\js\i18n\ grid.locale-en.js extracted location into the
Scripts -->JQGrid Folder.
So we are done with the script files, next is to add the css files.
Add the file \jquery.jqGrid-4.6.0\css\ ui.jqgrid.css into the styles folder in our solution.
After adding all these files our solution will look like below.
We are all set with the required files including JQuery file.
Now we can start assembling all these files in the Index.cshtml file, all these newly added files related to JQGrid has to be added inside the head tag of the Index.cshtml file as shown as below.
Then we have to add one table with id tblJQGrid for the JQGrid inside the Index.cshtml file, and bind the JQGrid with the table from JavaScript
So I've added a table with above mentioned id inside the Index.cshtml file also added the script to bind the table with JQGrid as below .
<script type="text/javascript">
$(document).ready(function () {$("#tblJQGrid").jqGrid(
{url: '',
datatype: "json",
mtype: 'GET',
colNames: ['Id', 'First Name', 'Last Name', 'Last 4 SSN', 'Department', 'Age', 'Salary', "Address", 'Marital Status'],
colModel: [
{ name: 'EmloyeeId', index: 'EmloyeeId', width: 20, stype: 'text' },
{ name: 'FName', index: 'FName', width: 150 },
{ name: 'LName', index: 'LName', width: 150 },{ name: 'SSN4', index: 'SSN4', width: 100 },
{ name: 'Department', index: 'Department', width: 80, align: "right" },
{ name: 'Age', index: 'Age', 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: 'EmloyeeId',
viewrecords: true,
sortorder: "desc",
caption: "List Employee Details",
scrollOffset: 0});
});
</script>
For further details on each and every attributes specified you can refer my previous article.
Using-JqGrid-in-ASP-NET
JqGrid-Inline-Editing
Ok, let’s go and run the application and see how it looks like .Whether the jqgrid is showing up or not.
Are you ready …?
I got something like above rendered on the UI.
Yea …
One thing we can say is that the grid is getting rendered without data, But … What about the style...
The CSS I mean...
Looks bad for me .What about you …?
Oops, I forgot one thing... I forgot to add the JQuery UI theme in our solution.
Let’s go and download the jQuery UI theme and see how our grid looks like.
Yea I got the link I’ve downloaded a theme that matches our css called Cupertino.
I go that downloaded as a zip file like the JQGrid files.
To accommodate this files we have to create a images folder inside our styles folder the add the entire images from the extracted location
\jquery-ui-1.10.4.custom\jquery-ui-1.10.4.custom\css\cupertino\images to our images folder inside the styles folder.
Then also add the css file
\jquery-ui-1.10.4.custom\jquery-ui-1.10.4.custom\css\cupertino\jquery-ui-1.10.4.custom.min
Hope you have done all these things…
Then try run the application once more and see how our grid looks like.
Looks really great…
Correct?
If you want to see my grid check out the below image.
Simply Awesome, right?
Did you felt any difference when you assembled JQGrid in ASP.Net application?
It’s same as that with minute difference.
Ok, anyway we are done with the second step also.
Binding Data with JQGrid
In my previous articles on JQGrid, I used Mongo DB as my db for ease of use .I got lots of questions from readers asking for code to connect with SQL server DB. So I thought of using SQL server here.
To do this, I’ve created a table that matches the schema of the grid called Employee and also a stored procedure to fetch data from the grid called spGetEmployee.
Before continuing further, please be aware that the DB did not follow any best practices, created just for demo purpose.
Let’s go and create a Data access layer (DAL) for database operations in our current solution by adding a class library project. I’ve created a DAL with name KDAL and inside that a class called KDATA to retrieve the employee data from the DB with the help of ADO.net Disconnected approach.
Please refer the below code which I've used to connect with my local DB.
namespace KDAL
{
public class KDATA
{
public static DataTable GetDataTable()
{
SqlConnection sqlCon = new SqlConnection("Data Source =(local);Initial Catalog=JQ GridDemo;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("spGetEmloyee", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
The above code will successfully return a data set for you if the name of the database matches with yours.
I tested the code, and it worked perfectly for me.
Then what we want next is to insert some dummy data to our database, Let's go ahead and do that.
I've created some dummy data with the help of notepad++ .
If you want the table and sp creation script along with dummy data, please take a look at DAL project for a text file with name CreateDbWithDummyData.txt .
What you have to do all is copy the script inside the text file and execute inside your SQL server.
After doing all these thing, just cross verify whether your DB is populated with enough data to be displayed.
For me everything is perfect and now am going to create a new controller to fetch data for the JQGrid.
Inside that controlled I'll call the data access method to fetch data then serialize that data into JSON format with the help of Newtonsoft dll.
If you are working with JSON serialization with default MVC JSON serialization mechanism, there is a chance of getting some exceptions like circular reference and all,to avoid that sought of tensions better use Newtonsoft dll.
What I've done here is just created a method inside the controller and fetch data then serialized that data into JSON string as below.
So we are ready with the JSON string here,next what we have to do is bind the JQGrid with the string data returned from this above method,For that we have to set the URL property of JQGrid as this newly created method.
Then try Run your application, whether it works or not.
What happened...?
Did that go well?
For me, it went well I got a grid as below.
So howz… that …?
We are done ....
Finishing note
While writing this article my target audiences are beginner’s in MVC application and with JQGrid.
I just wanted to set the stage for the beginner’s and intermediate developers to start using JQGrid with MVC and as a first volume of my coming articles.
hope you got what you want to start with.