Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Sunday, July 31, 2011

JqGrid in ASP.NET MVC3 Code First Project

JqGrid is one of the most popular and flexible Jquery based component which is available for ASP.NET and PHP. These components are for sale included in a bundle of other useful Jquery plugins such as JqChart, JqTreeGrid and many more. If you can afford, then you can buy the plug-in already integrated to ASP.NET MVC 2+. But for those who are interested to learn, Pinoy Brown Bag Sessions will show you how its done in a simple way. 
Using JqGrid in Asp.NET MVC 3 with VB.NET


I'v been using JqGrid plugin during my college years. The plug-in was still in its earlier version and is available opensource for PHP developers only. Back then, using JqGrid in ASP.NET was still an issue in forums and other blogs. a documentation of JqGrid for PHP is available in this website which I have used for 3 years by now and still it does work for me. 

For this brown bag session download the opensource demo package here. You can also download from github here. All you need to do is run the demo in your local server and try some of the examples provided for you. NOTE that the demo you downloaded is for PHP. Based on that demo we can arrive with a JqGrid in our ASP.NET MVC 3 project with VB.NET. 

To start lets create the view for the JqGrid. In our previews post I have already included the <div> with the id "jqgrid_product" for the grid view. The code is shown below. 

<div id="toystoregrid">
<table id="jqgrid_product" class="scroll" cellpadding="0" cellspacing="0" style="cursor: pointer;
-moz-user-select: none;">
</table>
<div id="jqpager_product" class="scroll" style="text-align: center;">
</div>
<input id="setcols" type="button" value="Set Columns" />
</div>

Next we then add the javascript for this plug-in to identify its properties such as column name, column format, caption and more. To do this lets insert a Jquery AJAX function just before the last closing div tag of our view in index.vbhtml file.

<script type="text/javascript">
$.getScript("@Url.Content("~/jsx/Home.js")");
</script>

This function loads a javascript file named Home.js in our directory. The purpose of this function was just actually to separate the javascript from the view or HTML in order to give you a clearer view on how its done. Next in our Home.js file lets add some Jquery and the JqGrid plug-in as well. Here is the code snippet for shown below.

Home.js

$(function () {
$("#jqgrid_product").jqGrid({
scrollrows: true,
url: "Home/jsontry",
datatype: "json",
colNames: ['ID', 'Name', 'Description', 'Price'],
colModel: [
{ name: 'Tbl_Id', index: 'Tbl_Id', width: 150, resizable: false, sortable: false },
{ name: 'Tbl_Name', index: 'Tbl_Name', width: 250, resizable: false, sortable: false },
{ name: 'Tbl_Description', index: 'Tbl_Description', width: 250, resizable: false, sortable: false },
{ name: 'Tbl_Price', index: 'Tbl_Price', width: 150, resizable: false, sortable: false }
],
mtype: "POST",
imgpath: 'themes/basic/images',
pager: $('#jqpager_product'),
rowNum: '10',
rowList: [10, 20, 30],
rownumbers: true,
viewrecords: true,
caption: "Sample JQgrid",
height: '200',
width: '1024',
autowidth: true
});
});

You can see from above the code snippet for our JqGrid. Notice that the JqGrid function is in-closed with a Jquery which is equivalent to a document.ready() function in javascript. If you downloaded the demo of JqGrid, the script shown above is the Loading Data demonstration on JSON. JavaScript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. I prefer JSON than XML in terms of speed and readability. Also that ASP.NET MVC 3 supports JSON. I will show you that not long from the code behind. 

Let me discuss some important lines with you as we go along. We have this line $("#jqgrid_product").jqGrid({, the id of the table we created earlier in our view. This identifies the target element of the plug-in. In order to connect to our database we have the URL given in this line url: "Home/jsontry",. The URL identifies "Home" which is the controller and "jsontry" which is that method that we will create later. colNames: and colModel: are the properties that identify our column and the model. You can read more about this properties in the documentation available in PDF format here. You can try to experiment with the other properties and see how it affects your grid. 

We are now ready to do the code behind. But first lets create a simple class that would contain the data that we return to our grid as JSON. The code blow shows the jqgriddata.vb class. 

jqgriddata.vb  

Public Class Jqgriddata
Private _id As Object
Private _cell As Object

Public ReadOnly Property id As Object
Get
Return _id
End Get
End Property

Public ReadOnly Property cell As Object
Get
Return _cell
End Get
End Property

Public Sub New(ByVal idpass As Object, ByVal cellpass As Object)
_id = idpass
_cell = cellpass
End Sub
End Class

I will discuss the two properties of the class later in this brown bag as we finish the code for the controller.

Now lets do code behind for our HomeController.vb. For those who have downloaded or created the project the code below will replace the code from your controller as we do the jquery method. For the first method we have this code below. 

Function Index() As ActionResult
Return View()
End Function

Function jsontry(ByVal data As FormCollection) As ActionResult
Dim page = data("page") 'the current page for paging
Dim limit = data("rows") 'number of rows per page
Dim sidx = data("sidx") 'pass the row value used for sorting
Dim sord = data("sord") 'sort order (asc or desc)
Dim countrows As Integer
Dim totalpages As Integer

If sidx.ToString <> "" Then
sidx = 1
End If
countrows = (From p In _entities.Products _
Select p).Count() 'linq query to count for number of rows
If countrows > 0 Then
totalpages = Math.Ceiling(countrows / limit)
Else
totalpages = 1
End If

If page > totalpages Then
page = totalpages
End If

Dim start As Integer
start = limit * page - limit

Dim result = (From p In _entities.Products _
Select p) 'the query to fetch the row values from the database

Dim cell = result.ToArray()
Dim celly = result.ToList()
Dim response As New Dictionary(Of Object, Object)
Dim rows As New ArrayList

response.Add("page", page)
response.Add("total", totalpages)
response.Add("records", countrows)

Dim i = 0
Dim x = 0
'some loop in order to extract the data from our entity to an arraylist
For Each row In cell
Dim cellx As New ArrayList
For Each c As System.Reflection.PropertyInfo In row.GetType().GetProperties()
cellx.Insert(i, row.GetType().GetProperty(c.Name).GetValue(row, Nothing))
i = i + 1
Next
rows.Insert(x, New Jqgriddata(row.Id, cellx)) 'the data is added to a Dictionary basically an array
i = 0
x = x + 1
Next
response.Add("rows", rows)
Return Json(response) 'return the response as JSON.
End Function

Wow! Quite a long VB script you have their. I added some comments though to discuss how the code behind produced the return value of the method. I only applied the PHP script and manage to somehow convert it to VB.NET. My first project doing this was with C# which was the easier version I guess. Yet here's a VB example for you VB users. With this code I am sure you can easily do it with C#.

And we are done with the the brown bag session. Try to run the code and with that your grid must appear smoothly in you index page. We just have made our JqGrid in ASP.NET MVC 3. I used firebug to display the post data from the grid as well as the response from the code behind. 

Sample JqGrid in ASP.NET MVC 3 with VB.NET.
I added some JqueryUI themes that you can download from their website. This is a Dot Luv theme from long ago. They have a lot more options to choose from with their latest version of JqueryUI nowadays. I also added a property from JqGrid which enables you to set the columns to display. Try to read and explore the documentation for this function. Here I have the image below.

JqGrid Set Columns function example.
You can view some result and also help you with debugging by using some tools like FireBug. If you are using  FireFox web browser the plug in is available from the website. Here are some results from my FireBug. 

JqGrid post data for the MVC controller method.

Some JSON results from ASP.NET MVC 3.
Other interesting results from FireBug.
That was all for now. I hope you have learned some few things from our short brown bag sessions. The next post will be on the CRUD. I will demonstrate how I used Jqury Populate and Validation in my ASP.NET MVC 3 application. Stay tune for more of Pinoy Brown Bag Sessions tutorials. Please feel free to as questions and feedback to improve the project. Thank you!

JqGrid in ASP.NET MVC3 Code First Project

JqGrid is one of the most popular and flexible Jquery based component which is available for ASP.NET and PHP. These components are for sale included in a bundle of other useful Jquery plugins such as JqChart, JqTreeGrid and many more. If you can afford, then you can buy the plug-in already integrated to ASP.NET MVC 2+. But for those who are interested to learn, Pinoy Brown Bag Sessions will show you how its done in a simple way. 
Using JqGrid in Asp.NET MVC 3 with VB.NET


Tuesday, July 26, 2011

Jquery AJAX with ASP.NET MVC3

The next series of brown bag sessions is about using Jquery AJAX with ASP.NET MVC 3. This project is the continuation of ASP.NET MVC 3 and Entity Framework Code First project. The methods I used in this project are undocumented. Feel free to apply or modify these tips and tricks to your own project. As we go along with the topic I will include the references of the plug-ins used for you to study and download the source. It is recommended that you enhance the methods and the code structure for production purposes. Greate! Let the learning begin!

Using Jquery AJAX with ASP.NET MVC 3



Figure 1. ASP.NET MVC 3 Script folder
My journey with Jquery started two years ago back in my college days. Jquery is a fast, concise, library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX. Sounds good! No wonder why ASP.NET MVC comes with Jquery as well. Figure 1 shows the Script folder of the MVC project. The once that are highlighted are the javascript files from the ASP.NET MVC framework while the others are just added for the purpose of this demonstration. you can see the Jquery library and other jquery plug-ins that are available for this framework and that these js files are already integrated to your created project. So far, for this version of the MVC framework the latest virsion of Jquery is 1.4.1. As you can see I have added a newer version of Jquery in this project which is 1.4.2. You can checkout the Jquery website for more updates with the library which as of this date is in version 1.6.2. Their might be some compatibility issues with the MVC 3 framework and for that please refer to the documentation provided at their website.

Let us begin the demonstration by making a backup copy or our previews project. If you have read my previews post on the ToyStoreMVC3 project then you can modify that one for this project. But I suggest to backup the old one just in case you need a reference on the view scaffolding method.

Navigate to Views >Shared and open _Layout.vbhtml. This is the main page which contains the head and the body of your HTML. It is used as the master page which will load the views dynamically in its content. Lets include the necessary js and css files needed for the project.

<head>
<title>@ViewData("Title")</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/Jqueryui/jquery-ui-1.7.1.custom.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/ui.multiselect.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/jquery-1.4.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
@*JSON*@
<script src="@Url.Content("~/Scripts/jquery.json-2.2.min.js")" type="text/javascript"></script>
@*Jquery Validation*@
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
@*Jquery Populate*@
<script src="@Url.Content("~/Scripts/jquery.populate.min.js")" type="text/javascript"></script>
@*JqGrid*@
<script src="@Url.Content("~/Scripts/Jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Jqgrid/jquery.jqGrid2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Jqgrid/ui.multiselect.js")" type="text/javascript"></script>
</head>

This is the head tag and the scripts I used. Notice the src and href properties of the script and link tags. The method use Razor to give the URL value of the file. Also I included some Jquery plug-ins that will be used in this demo. We have Json, Jquery Validation, Jquery Populate, and JqGrid. I'll tackle each of the plug-ins as we go along.

View - Jquery Style

In the previews brown bag session, we learn about scaffolding views with ASP.NET MVC 3 framework. This time I will show you how to use Jquery with the view to manipulate the containers and do some animation just for fun. To start with lets delete the views we have created using the scaffold method. Navigate to Views > Home folder and remove the following files shown in Figure 2.

Figure 2.  Create, Delete, Details and Edit views.
Now you are suppose to be left with these files in the Views folder as shown in Figure 3.

Figure 3.  Views folder for Jquery project.
Index.vbhtml

In this project I will be using the Index.vbhtml file as a view. This view will carry out the CRUD (Create, Read, Update, Delete) function with the help of Jquery AJAX. As I have said a while ago, the method used is undocumented. I'd be open for discussions and corrections who might have some interesting ideas regarding this topic. Ok! here is the code for my view.

@Modeltype ToyStoreMVC3.Product
@Code
ViewData("Title") = "Home Page"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<h2>
Home</h2>
<input id="butCreate" type="button" value="Create" />
<input id="butEdit" type="button" value="Edit" />
<input id="butDelete" type="button" value="Delete" />
<div id='ajaxpage'>
<div id="toystoregrid">
<table id="jqgrid_product" class="scroll" cellpadding="0" cellspacing="0" style="cursor: pointer;
-moz-user-select: none;">
</table>
<div id="jqpager_product" class="scroll" style="text-align: center;">
</div>
<input id="setcols" type="button" value="Set Columns" />
</div>
<div id="toystorediv" style="display: none">
<form id="toystoreform">
<fieldset>
<div id="preloader" style="display: none">
<img src="../../Image/loader2.gif" /></div>
<input id="Id" name="Id" type="hidden" value="" />
<div class="editor-label">
@Html.LabelFor(Function(model) model.Name)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Name" name="Name" type="text" value="" />
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.Description)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Description" name="Description"
type="text" value="" />
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.Price)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Price" name="Price" type="text"
value="" />
</div>
<input id="butSave" type="submit" value="Save" />
<input id="butCancel" type="button" value="Cancel" />
</fieldset>
</form>
</div>
</div>

Most of it are just containers that will be used by the application to display the Product form and the Product Grid. As we go on with the brown bag session I will tackle each of these containers and how to handle them with Jquery.

That was it for now. I hope that this post already gave you an overview of the project. Try to run the project and see the result of the view we've just created. The next post will be on using JqGrid on ASP.NET MVC 3. Stay tune for more!

Jquery AJAX with ASP.NET MVC3

The next series of brown bag sessions is about using Jquery AJAX with ASP.NET MVC 3. This project is the continuation of ASP.NET MVC 3 and Entity Framework Code First project. The methods I used in this project are undocumented. Feel free to apply or modify these tips and tricks to your own project. As we go along with the topic I will include the references of the plug-ins used for you to study and download the source. It is recommended that you enhance the methods and the code structure for production purposes. Greate! Let the learning begin!

Using Jquery AJAX with ASP.NET MVC 3

Saturday, July 2, 2011

ASP.NET MVC 2 and Jquery AJAX Integration

In this post I will be showing you a video which i have made a while ago in the first release of ASP.NET MVC 2. This video will help you learn and understand how to integrate Jquery AJAX to your ASP.NET MVC 2 application. This post will be followed by other ASP.NET MVC 3 projects using plugins made with Jquery.





ASP.NET MVC 2 and Jquery AJAX Integration

In this post I will be showing you a video which i have made a while ago in the first release of ASP.NET MVC 2. This video will help you learn and understand how to integrate Jquery AJAX to your ASP.NET MVC 2 application. This post will be followed by other ASP.NET MVC 3 projects using plugins made with Jquery.





You might also like:

Related Posts Plugin for WordPress, Blogger...