I made helper available as part of my Lib.Web.Mvc library, and you can download it here (source code included), or go for the NuGet package.

public class ProductViewModelFollowing standard DataAnnotations attributes are supported:
{
#region Properties
public int Id { get; set; }
public string Name { get; set; }
[JqGridColumnSortingName("SupplierId")]
public string Supplier { get; set; }
[JqGridColumnSortingName("CategoryId")]
public string Category { get; set; }
[DisplayName("Quantity Per Unit")]
[JqGridColumnAlign(JqGridColumnAligns.Center)]
public string QuantityPerUnit { get; set; }
[DisplayName("Unit Price")]
[JqGridColumnAlign(JqGridColumnAligns.Center)]
public decimal? UnitPrice { get; set; }
[DisplayName("Units In Stock")]
[JqGridColumnAlign(JqGridColumnAligns.Center)]
public short? UnitsInStock { get; set; }
#endregion
#region Constructor
public ProductViewModel()
{ }
public ProductViewModel(Product product)
{
this.Id = product.Id;
this.Name = product.Name;
this.Supplier = product.Supplier.Name;
this.Category = product.Category.Name;
this.QuantityPerUnit = product.QuantityPerUnit;
this.UnitPrice = product.UnitPrice;
this.UnitsInStock = product.UnitsInStock;
}
#endregion
}
- DisplayName - This will set the name for the column (default is property name).
- DisplayFormat - Value set for NullDisplayText will be used as cell value if property value will be null. Value set for DataFormatString will be used for formatting property value (on server side).
- HiddenInput - This will set JqGridColumnModel.Hidden to true.
- Range - Value set for Maximum will be used for EditRules.MaxValue of editable column and value set Minimum for will be used for EditRules.MinValue.
- Required - This will set EditRules.Required to true for editable column.
- ScaffoldColumn - If set Scaffold to false, there will be no column created for property with this attribute.
- StringLength - Value set for MaximumLength will be used for EditOptions.MaximumLength of editable column.
- JqGridColumnLayout - This will set the layout attributes for the column (alignment, initial width etc.).
- JqGridColumnSortable - This will set the sorting options for the column (by default every column is sortable with property name as sorting name).
- JqGridColumnFormatter - This will set the predefined (with options) or custom formatter for the column.
- JqGridColumnEditable - This will set the edit options for the column.
- JqGridColumnSearchable - This will set the search options for the column.
<link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/jqGrid/jquery-ui-jqgrid.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.jqGrid.locale-en-3.8.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.jqGrid-3.8.2.min.js")" type="text/javascript"></script>Then we can instantiate the helper and set desired options: @{
var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper<jqGrid.Models.ProductViewModel>("products",
dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
pager: true,
rowsNumber: 10,
sortingName: "Id",
sortingOrder: Lib.Web.Mvc.JQuery.JqGrid.JqGridSortingOrders.Asc,
url: Url.Action("Products"),
viewRecords: true
);
}This instance can be used for rendering HTML and JavaScript required by jqGrid:@grid.GetHtml()All we have to do now is creating an action method, which will provide data for our grid:
...
<script type="text/javascript">
$(document).ready(function () {
@grid.GetJavaScript()
});
</script>
[AcceptVerbs(HttpVerbs.Post)]When you run it, you should see something similar to this:You can download a sample project for this helper, which contains following examples:
public ActionResult Products(JqGridRequest request)
{
int totalRecordsCount = _productsRepository.GetCount();
JqGridResponse response = new JqGridResponse()
{
TotalPagesCount = (int)Math.Ceiling((float)totalRecordsCount / (float)request.RecordsCount),
PageIndex = request.PageIndex,
TotalRecordsCount = totalRecordsCount
};
response.Records.AddRange(from product in _productsRepository.FindRange(String.Format("{0} {1}", request.SortingName, request.SortingOrder), request.PageIndex * request.RecordsCount, request.RecordsCount)
select new JqGridRecord<ProductViewModel>(Convert.ToString(product.Id), new ProductViewModel(product)));
return new JqGridJsonResult() { Data= response };
}
- Basics & Formatting
- Configuration Import/Export
- Cell Editing
- CRUD - Inline Editing
- CRUD - Form Editing
- Searching - Single
- Searching - Toolbar
- Searching - Custom
- Searching - Advanced
- Subgrid
- TreeGrid

Email
73 comments:
What about license for this helpers?
I am not sure that you can publish this code....
Maxim.
The Lib.Web.Mvc which I'm publishing under Ms-PL license has been created by me and it doesn't contain any third party elements (it is built "on top" of .Net Framework and ASP.NET MVC). The jQuery plugins used in sample application (including jqGrid) are licensed under GPL and MIT license which generally makes them available to everyone for free. So what is your concerne about?
Nice work!
Tomasz - you are right. Sorry for trouble.
Hey Your Libs is Perfect. I love JQGrid, I have a trouble, can u post a demo with form edit with image_upload, or integrate tinymce into jqgrid form edit.
Thanks.
I will try to find some time and create such a demo.
@DungDepTrai The sample you asked for is ready, you can read about it here --> http://tpeczek.blogspot.com/2011/03/jqgrid-and-aspnet-mvc-form-editing-with.html
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog.
Good stuff, thanks very much for making this available to the .Net community! I also like your example code demonstrating how to use it, very well done.
I'm from Texas, USA and visited Warsaw and Torun in the mid '90's and had a great time there.
Cheers,
James
Hey man your project is awesome i have downloaded a example with mvc grid strongly typed helper, i see you have awesome blog post about it.
i just want to know what do we have to setup to run it on our machines, i have try it but i get errors like: The provider did not return a ProviderManifestToken string.
Can you help about it?
Cheers!
Sample project requires Northwind database, you can download it here. After download you need to set it up and configure ConnectionString properly.
I have downloaded and run the demo. Thanks for the great work. Question: If I want to display an url link in the leaf node of the tree, rather than text, is that possible? or does jqGrid itself only supports text for each cell?
Thanks.
I'm not sure, I will have to test it.
Too bad i must stick with .NET 3.5 :/
Do you think it would be complicated to rewrite your lib for 3.5 ?
It should be possible, but it will be a considerable amount of work.
Really awesome library btw...
First, The solution example does not contain the Northwind projects or dll's. Are those downloadable or are they your source?
Second, Does your library support configuring a search field as a drop down list?
THX
-Ben
Hi,
I have updated samples release with missing projects so you can download it again. You still need to download Northwind database from Microsoft download page.
If it comes to configuring search field as drop down list it is supported, there are two configured like this in sample project.
Hi,
Really awesome control.
Is it possible to export the grid contents to excel?
Thanks,
-Naren
Hi,
There is no ready to use method for exporting jqGrid to Excel. All solutions I have seen are just adding custom navigator button which calls server side functionality for generating excel file with the same data.
Regards,
Tomasz Pęczek
Hey Tomasz, thanks for sharing your great jqgrid helper! After setting up a project to use it, I ran into an issue where if the Id field for my model isn't set to "Id" but lets say "BonusId" an update from the jqgrid will not set the BonusId field on my object, but if I change my model to use "Id" it seems to work perfectly. Is there a way to use your helper with this naming convention? Thanks in advance!
Hi Steve,
You can use parametersNames parameter of JqGridHelper constructor to redefining how jqGrid will pass the "id" in all edit modules:
var grid = new JqGridHelper("id", ..., parametersNames: new JqGridParametersNames() { Id = "BonusId" }, ...);
That did the trick! Thanks again! :D
Hi Tomasz,
First of all thanks for such great library. Its really worth.
Just a questioin from first look as i have used other libraries to analyze. Can't we use rowObject.ModelParameter for the formatter as it seems that the generated Json data do not contains the column information.
Like in your example, can i not use rowObject.Name in custom formatter. If can use, could you please let me know how to do it.
Hi Manish,
The jqGrid json reader can work in two modes, depending on repeatitems value. In first (repeatitems = true, this is what helper is using) the data are posted as arrays of strings, and you can access those by index (rowObject[1]). In second (repeatitems = false) the data are posted as objects and this is what you are reffering to. If support for repeatitems = false is important to you please create me an issue on codeplex and I will work on having both options available.
HiTomasz,
Thanks for quick response.
We have analyzed and found that there are some things that we have difficulties with:
Like,
- columnname from resources
- accessing columns using rowobject.columname
- Dynamic assignment to columnnames, like we are showing report for the week and we want to show dates in header
Anyway, I will look forward to and watching this on codeplex. Hopefully we can use it in future.
Hi Manish
The first thing should be possible by using Display attribute from System.ComponentModel.DataAnnotations (.Net 4.0 and ASP.NET MVC 3). The second thing as I described will require access to jsonReader options (which is planned in future, now you only have the indexes option). The dynamic column names are possible by subclassing DisplayNameAttribute (because attributes requires constant expressions for parameters this is only way).
Hi
Any plans to release the client side code in ASPX?
I am trying to convert the Razor code and having a little difficulty with how to reference to the grid variable in the Javascript. I am getting variable undefinded.
Thanks in advance!
Ian
This is server side helper which generates jqGrid javascript which is ASPX/Razor independent.
Hi Tomasz,
Great stuff! I have been in Silverlight land and loving it, however, MS pulled the rug out of us SL developers and I am digging into MVC 3, HTML5, CSS3, jQuery (yea, it takes all that stuff to build an application, where as in SL you just needed XAML and C#) and feel like I have been dropped into the abyss. Your examples are awesome and your helpers are awesome. I just downloaded all of them and will be burying my head into them for the next week as they are the best samples I have found. Thanks for some great work.
Hi Keith,
Thanks for a good word, I'm always happy to help.
How do I set the jqGrid rowList option within JqGridHelper?
This option is available since Lib.Web.Mvc 4.0.0, you can use it like this:
rowsList: new List<int> { 10, 15, 20, 25, 30 }
Brilliant Work !
Thank you for this :-)
I had a problem with the JSON,
the data items in a row were getting serialized in the wrong order
They seemed to be order by the order they were defined in my 'TModel' class .. :-( ...
So data was appearing in the wrong columns
but managed to fix it in my controller using
(you'll have to forgive the VB ;-) )
Function Contacts(request As [Lib].Web.Mvc.JQuery.JqGrid.JqGridRequest) As ActionResult
....
Dim response As New [Lib].Web.Mvc.JQuery.JqGrid.JqGridResponse
With response
.......
.Reader.RepeatItems = False
End With
Return New [Lib].Web.Mvc.JQuery.JqGrid.JqGridJsonResult With {.Data = response}
End Function
It was the ".Reader.RepeatItems = False" bit that fixed it
It's increased the size of the JSON .. but it works :-)
Thankyou again
Stu
Hi..great job!!! i have a question, sorry by poor English ;)
How can i do, show a view in the modal dialog ? a example be appreciated.
Regards
Jorge
Hi,
Sorry but your question is unclear for me. Please feel free to contact me via email to clarify the problem.
Regards,
Tomasz Pęczek
@Tomas
Great plugin, man! It must admit that i only considered using jqGrid because of your project on codeplex. It's been very useful. I hope you continue to add more features :)
@Jorge
Amigo, se quiseres eu posso te enviar um exemplo de como põe uma View dentro de uma modal utilizando o jqGrid. Não é tão difícil assim, basta usar o jQuery Dialog com os eventos do jqGrid ao selecionar um Row ou mesmo clicar num CustomButton. Passa teu email que eu te mando o exemplo na boa :)
Excelente AdrianoRR, gracias por la info... mi correo es
heredisoft@gmail.com
@Tomasz
How can use a filterExpression to compare Datetime? with string? When i try to filter data values, the linq dynamic extension always thrown a ParseException saying that: Operator '<=' incompatible with operand types 'DateTime?' and 'String'
@AdrianoRR
If you create rule like below, it will work (of course you need string in correct format for Convert.ToDateTime):
.Where(String.Format("ShippedDate >= Convert.ToDateTime(\"{0}\")", "05/01/1998"))
@Tomasz
Hey, thanks. I was trying to convert the datetime to string to do the comparison. Never occurred me to actually compare the datetimes.
Now i'm struggling to fit the filterExpression into a inner join using linq to sql.
This project is really awesome and the examples are simply superb.
Thank you for your work
@Tomasz
I understand that maybe this is not entirely connected to your framework. Even so, i'd like to ask how can i perform a groupBy. So far, i've struggling against it because of linq extensions says that No property or field '<>' exists in type 'IGrouping`2.
Do you know how to solve it or where should look for it?
Thanks
@AdrianoRR
Hi, can you share some source code to analysis? Please feel free to contact me via email for easier communication.
@Tomasz
My previous question was a dumb one, not really related to your framework but to dynamic linq.
This new one, however, is related :)
Do you know how to cache the ActionResult responsible to fill the data for a jqGrid? Since it uses a complex object (JqGridRequest), how would you perform the caching? Right now, everytime a user clicks on a link that leads to a grid on my system, the ActionResult calls the method responsible to fill jqGrid's data.
Any tips?
It all depends on which level you want to perform caching:
- Browser Cache
- ASP.NET Output Cache
- ASP.NET Application Data Cache
Oops, i forgot to mention in what level i was trying to do it. Since i have a small server, i won't be very interesting to have a Application Cache.
I was trying to use the default [OutputCache] Attribute, with duration and VaryByParam (jqGridRequest), on client level.
So to answer your question, i'd say that i want to perform it on Browser and ASP.NET Level.
In VaryByParam you must specify actual keys from request POST collection, for example this will work:
[OutputCache(Duration = 60, VaryByParam = "page")]
You must also remember that jqGrid is adding dummy parameter nd which have random value in every request.
Which means that for every random dummy parameter it will generate a cache, right?
If that's right, there's no way to use OutputCache with jqGrid framework? Will i have to use Caching Application Block from the Enterprise Library?
OutputCache can be a reasonable solution if you are not implementing searching - that would limit caching to only page and sorting parameters. In other case I would suugest application level cache (Caching Application Block might be option here).
@Tomasz
Thanks for the answer. I've been reading a lot about caching on asp.net and found that ppl are using Runtime.Caching now, which is a better solution than the former Web.Caching.
However, i still don't know how to change the cache for each user. It would be a cache per user acessing the jqGrid, not for the entire application.
I downloaded the sample project for razor and it works fine. However when I tried to use Lib.Web.Mvc in my own project. I got this error: The type 'System.Web.Mvc.JsonResult' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
I think it is because that your dll looks for System.Web.Mvc in GAC. But we have it in a shared referencedll folder. Do you have a version that not looking for System.Web.Mvc in GAC? I tried to use Assemblybinding but it does not work.
Your help is highly appreciated.
Lib.Web.Mvc is holding standard reference to System.Web.Mvc so it should be resolved in standard way (not forcing GAC). The library was tested in enviroment where ASP.NET MVC wasn't installed in GAC. Such error might appear if you are using ASP.NET MVC 2 or ASP.NET MVC 4 (without assembly binding). In worst case scenario you can always built the library for yourself - every release on CodePlex contains full source code.
Hi,
I want to add sub total & grand total
row in jqgrid, I am using MVC, kindly
give any idea about it,
Thanks in advance.......
Hi,
An easy way for creating sub totals might be grouping, take a look here: http://tpeczek.blogspot.com/2011/07/jqgrid-strongly-typed-helper-caption.html. As for the total, you can use the footer (you can take a look at Formatting.cshtml in my repository to se how it gets done: https://tpeczek.svn.codeplex.com/svn/trunk/MVC/jqGrid%20Helper%20Examples/jqGrid/Views/Home/). If you have any more questions please fell free to start a discussion on tpeczek.codeplex.com or send me an email.
Hi Tomas,
Thank you for this ! :)
I'm not sure how you add events
in the jqHelper declaration
below I tried to add ondblClickRow function to open Edit Dialog when double clicking in row.
var grid = new JqGridHelper
("tblEmployees", // table id
dataType: JqGridDataTypes.Json,
methodType: JqGridMethodTypes.Post,
pager: true,
rowsNumber: 10,
sortingName: "LastName",
sortingOrder: JqGridSortingOrders.Asc,
url: Url.Action("FindEmployees"),
width: 1077,
viewRecords: true
, ondblClickRow: function(){
var row_id = jQuery(this).getGridParam("selrow");
jQuery(this).editRow(row_id, true);
}
)
Thanks, LA Guy
The JavaScript for the events should be passed as string to .Net object properties.
hi!in the jqrid if i want to send like two parameters to the controller i can use for that postData in this way PostData:{myparam:“myvalue”}
But i dont know how to make this work using your helpe
im the anonymous from before, i explain better the case.
I have a dropdownlistfor, and a jqgrid.My idea is that depending of the selection of the dropdonlist the data of the jqgrid have to change.
so the method in the controller have to be something like this
public ActionResult Vendor(JqGridRequest request,Guid entityId)
But i dont know how to pass the entity id to the controller, i supose that have to be made with postData, but i dont know how make it works with the helper.Can you help me?
@Anthony
The three last posts of below thread should give you the solution you are looking for:
http://tpeczek.codeplex.com/discussions/348683
I have some problem initializing the variables.
I have this
@{
var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper("vendormapping",
dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
pager: true,
rowsNumber: 10,
sortingName: "Id",
sortingOrder: Lib.Web.Mvc.JQuery.JqGrid.JqGridSortingOrders.Asc,
subgridEnabled: true,
subgridModel: new Lib.Web.Mvc.JQuery.JqGrid.JqGridSubgridModel(),
subgridUrl: Url.Action("ProductMapping"),
url: Url.Action("VendorMapping"),
postDataScript: "{entityId: entityId}",
viewRecords: true
);
}
after in the script
$(document).ready(function () {
var entityId=50;
@grid.GetJavaScript();
});
$(function() {
$('#entity').change(function() {
var entityId=document.getElementById('entity').value;
$("vendormapping").trigger("reloadGrid") ;
});
});
where is the problem?
@Anthony
The problem is that your scenario is a little bit different than Lotux. He is reinitializing jqGrid with every change event while you are only reloading it. In that scenario jqGrid holds the initial value of postData until you change it (this is nothing related to helper). You have two solutions for this, first is to use function for postData (it will be called every time its need to be populated):
postDataScript: "function() { return { entityId: document.getElementById('entity').value }; }"
Second solution is to change the postData manually before reloading like this:
$('#vendormapping').jqGrid('setGridParam', { postData: { entityId: entityId } });
$('#vendormapping').trigger('reloadGrid');
At this moment I have this
@{
var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper("vendormapping",
dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
pager: true,
rowsNumber: 10,
sortingName: "Id",
sortingOrder: Lib.Web.Mvc.JQuery.JqGrid.JqGridSortingOrders.Asc,
subgridEnabled: true,
subgridModel: new Lib.Web.Mvc.JQuery.JqGrid.JqGridSubgridModel(),
subgridUrl: Url.Action("ProductMapping"),
url: Url.Action("VendorMapping"),
postDataScript: "{entityId: entityId}",
viewRecords: true
);
}
script
$(function() {
$('#entity').change(function() {
var entityId=document.getElementById('entity').value;
@grid.GetJavaScript();
$("vendormapping").trigger("reloadGrid");
});
});
$(document).ready(function () {
// var entityId=document.getElementById('entity').value;
// grid.GetJavaScript();
});
If i try your two solutions im continue having the same problem, only the first time that i change the selection of the combo the controller is invoked, but the changed function is called everytime, that i change the seletion.any idea?
So I see you are still mixing the approaches a little bit. If you want to reinitialize the entire jqGrid on every change event, you need to destroy the previous one with GridUnload method first:
$('#vendormapping').jqGrid('GridUnload');
You can skip the reloadGrid method in that case (btw. take an exact look at your jQuery selector for jqGrid element, in your code it is always wrong).
If you continue to have issues please write me an email with you scenario (as your post are incosisten and I no longer know if you want to have the grid preintialized or not) and I will get more detailed sample for you.
Hi Tomasz, You are an angel. Thanks for doing a great job.
2 questions:
1-I want to display a grid with only 3 columns out of total of 10 columns. If I select a record to edit a record I want to see all the 10 fields so that I can update them. How do I do that? Similarly when I Create a new record, I don't want all the 10 fields be displayed in my Grid, but only 3 out of 10.
2- Does your JQGrid support restful. My application is restful oriented and I cann't afford to use 2 method types of Post ( one for your jgrid action another to add new record, knowing that Post is used only to post a new record.
Hi,
First of all jqGrid isn't my creation, I have only created the helper. Now back to your questions:
Ad. 1 - This is possible only in form editing. You can use HiddenInputAttribute to hide column from displaying and then EditHidden property on JqGridColumnEditableAttribute to make that column visible in add/edit form.
Ad. 2 - You can control the HTTP method used for getting data by methodType parameter of the helper. The methods for the navigator actions (Add, Edit, Delete) can be controled with JqGridNavigatorModifyActionOptions.MethodType property.
All those options are described in documentation available through CodePlex download.
Tomasz: i have a question about JqGridColumnEditTypes.Select, there are any way to enable multiple select on Select
Like:
[JqGridColumnEditOptions(Multiple = true)]
tanks in advance
@Guillermo: You should be able to achieve this with HtmlAttributes option of JqGridColumnEditableAttribute. Please read more here: http://tpeczek.codeplex.com/discussions/347754
Tomasz sorry but I can not understand too much the example, I'm new programming in MVC and using your library, I created a question on StackOverflow about this, you can help to create the property
Hi,
I want to salute you for excellent work. I am using in my current project and I am having issues with checkbox, it returns values in the form of yes and no, whereas my viewmodel is looking for true and false values. In jqgrid there is option to use editoptions and you can set value for checked value. Do we have similar option in jqgrid strong typed helper. Please advise.
Thanks
Sanjay
Hi,
You can use Value property of JqGridColumnEditableAttribute in exactly the same way.
Hey Tomasz! awesome!!! Greetings from Mexico. I will use your job. Tell you later how goes. :D
Ӏt's remarkable in favor of me to have a web page, which is useful in support of my know-how. thanks admin
Here is my web site :: Lloyd Irvin
Post a Comment