Using NetAdvantage jQuery Grid in ASP.NET MVC

The NetAdvantage for jQuery product contains a client-side jQuery grid with an ASP.NET MVC Html Helper. The Helper makes it easy to new up the grid within your MVC views connecting to data form your model. In this blog, you will learn how to create a simple grid using the Razor syntax in your ASP.NET MVC view and connect to the data source.

Setting up the project

In order to get the grid to show up you will need the necessary JavaScript and CSS file on the client so that when the MVC helper generates the jQuery grid initialization code on the client, everything needed for the grid to display is available. When you create a new ASP.NET MVC 3 project it comes with Scripts and a Content folders where all the default JavaScript files and CSS contents are located respectively. We will use the same folder and insert the Infragistics Scripts & CSS.

image

Note: These Scripts & CSS can be found under the Install location of NetAdvantage for jQuery.

Next you want the project to be able to consume these references. You have two choices, use _Layout.cshtml and put everything there, or add reference on every page that uses an Infragistics control. I prefer to use the _Layout.cshtml because that way, I can just put this code at one place and don’t have to worry about it anymore in any other views I create that use Infragistics controls.  The following code in the head section of _Layout.cshtml will be needed:

 






You will also have to add reference to the Infragistics.Web.Mvc assembly that contains the Html Helper we will use in our Razor view. This contains definitions for all the MVC helpers, so once you have added this to your project, you will be able to work with all the controls throughout the project.

image

The project is now setup and we can build out MVC view with any Infragistics controls using the appropriate HTML Helper. For this blog, we will be using the Helper for the grid and have it display data coming from our Model.

Model

The ASP.NET MVC project has a default Model class called AccountModel.cs. In the same Model class, we will add a BankAccount object with some properties and a new AccountModels class that has a GetAccountList method which creates a list of BankAccout objects and returns them as a list of IQueryable objects. Using IQueryable object, the grid is able to natively perform operations like sorting, filtering and paging on the collection. You can use any type of collections, even web services to connect data and operate on the grid. The code we will add to AccountModel.cs class would be:

public class BankAccount
{
    public int AccountNumber { get; set; }
    public string AccountName { get; set; }
    public DateTime AccountDate { get; set; }
    public string AccountType { get; set; }
    public decimal AccountBalance { get; set; }
}

public class AccountModels
{
    public static IQueryable GetAccountList()
    {
        List accountList = new List();
        DateTime date = DateTime.Now;
        for (int i = 1; i < 1001; i++)
        {
            accountList.Add(new BankAccount()
            {
                AccountNumber = i,
                AccountName = "Test" + i.ToString(),
                AccountDate = date,
                AccountType = "chk",
                AccountBalance = 12345678.90M
            }
            );
        }
        return accountList.AsQueryable();
    }
}

View

We have already referenced the JavaScript & CSS in _Layout.cshtml, so now we can get directly to writing our view code. We will be using the Razor syntax to create the grid in the Index.cshtml page that gets generated when you create a new ASP.NET MVC 3 project, and binding it to the BankAccount object collection in the model. In order to be able to do that, we will need to insert the following lines right at the top of our view.

@using Infragistics.Web.Mvc;
@using Mvc3WebApp.Models;

Once we have these lines, we also get Visual Studtio intellisense that will make it easy to work with the helper and create views with the Infragistics jQuery grid or any other control. We can use the Html Helper to define grid properties, enable features and setup up the initial layout. We will begin with setting up column object, and setting some properties on it, enable paging, sorting & selection feature of the grid and use the “DataSourceUrl” property to connect it to the GetAccountList method which returns the list of BankAccount object. Finally we will call databind & render which is needed so that the grid can bind to its data source and render on the page. With all that, the helper will look like the following:

@( Html.Infragistics().Grid()
    .ID("igGrid1")
    .Columns(column =>
    {
        column.For(x => x.AccountNumber).DataType("int").HeaderText("Account Number");
        column.For(x => x.AccountName).DataType("string").HeaderText("Account Name");
        column.For(x => x.AccountDate).DataType("date").HeaderText("Account Date");
        column.For(x => x.AccountType).DataType("string").HeaderText("Account Type");
        column.For(x => x.AccountBalance).DataType("number").HeaderText("Account Balance");
    })
    .Features(features =>
    {
        features.Paging().PageSize(20).PrevPageLabelText("Previous").NextPageLabelText("NEXT");
        features.Sorting().Mode(SortingMode.Single).ColumnSettings(settings =>
        {
            settings.ColumnSetting().ColumnKey("AccountNumber").AllowSorting(true);

        });
        features.Selection().MouseDragSelect(true).MultipleSelection(true).Mode(SelectionMode.Row);
    })
    .ClientDataSourceType(ClientDataSourceType.JSON)
    .DataSourceUrl(Url.Action("GetAccountList"))
    .Width("100%")
    .Height("350")
    .LocalSchemaTransform(true)
    .DataBind()
    .Render()  
)

Controller

The grid MVC helper above will call the GetAccountList() method in the controller to get the data to display in the grid. We can setup the method, make the call to the GetAccountList in our Model and return the view back to the grid, so that it has what it needs. The Controller method do so will be:

[GridDataSourceAction]
public ActionResult GetAccountList()
{
    return View(Models.AccountModels.GetAccountList());
}

That is it. You can run the project and it will show the Infragistics jQuery grid control, connected to the data coming from our Model. You can perform operations like paging, sorting and selection, and the grid will function as expected.

image

Summary

In this article, you learned how to get started with the Infragistics ASP.NET MVC Html Helper for the jQuery grid control. Add project references, use the new Razor syntax for the MVC view, you can connect the grid to the data in the model and have it perform paging and sorting operations on that data.

You can download the sample code from here. If you have any questions on this blog, or questions in general about the Netadvantage for jQuery product, feel free to reach out to me. murtazaa@infragistics.com


Comments  (22 )

Shyam
on Fri, May 20 2011 12:23 AM

Hi Murtazaa, I am able to bind webdatagrid with above binding method and also with Normal code like  

<%  

       this.wgProject.DataSource = this.Model.lstProject;

       this.wgProject.DataBind();

%> and in Controller I am doing like this  public ActionResult ActiveProjects()

       {

           var vm = new ProjectDropDownVM();

           string sOrgId = "abe";

           vm.lstProject = _projectService.GetProjectNames(sOrgId);

           return View(vm);

       }

I can bind grid

but my point is when i bind drop down with same way and on dropdown change want to bind grid how it is possible to implement this code.

Anthony Queen
on Thu, Jun 9 2011 12:30 PM

works fine when running from the IDE. I published to an IIS6 win2k3 server to show another developer and I get an JSON Undefined error. Everything else on the site is working though.

The exact error is:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)

Timestamp: Thu, 9 Jun 2011 16:37:14 UTC

Message: The remote request to fetch data has failed:  (parsererror) 'JSON' is undefined

Line: 1

Char: 204959

Code: 0

URI: etnsys04/.../ig.ui.min.js

[Infragistics] Murtaza Abdeali
on Thu, Jun 9 2011 1:13 PM

@AnthonyQueen - Can you take a look at the sample in FireBug and check the response details when the grid is making the call to get its data? It will give you the details, which will help diagnose/fix the problem.

-Taz.

Anthony Queen
on Thu, Jun 9 2011 1:36 PM

In firebug (great tool!),

Under Inspect->Console

I see one node "getMVC3Test/Home/getAccountList?=1307641088535&page=0pageSize=20

Then under the JSON tab, I see 20 records (0 to 19) with TotalRecordsCount = 1000

So, it appears that I'm getting data, though the grid is still empty.

I still get the error (+1 from firebug):

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MS-RTC LM 8)

Timestamp: Thu, 9 Jun 2011 17:43:11 UTC

Message: The remote request to fetch data has failed:  (parsererror) 'JSON' is undefined

Line: 1

Char: 204959

Code: 0

URI: etnsys04/.../ig.ui.min.js

Message: Object doesn't support this property or method

Line: 7410

Char: 32

Code: 0

URI: getfirebug.com/firebug-lite.js

Anthony Queen
on Thu, Jun 9 2011 1:38 PM

BTW, This is the "Response":

{"Records":[{"AccountNumber":1,"AccountName":"Test1","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":2,"AccountName":"Test2","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":3,"AccountName":"Test3","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":4,"AccountName":"Test4","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":5,"AccountName":"Test5","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":6,"AccountName":"Test6","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":7,"AccountName":"Test7","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":8,"AccountName":"Test8","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":9,"AccountName":"Test9","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":10,"AccountName":"Test10","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":11,"AccountName":"Test11","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":12,"AccountName":"Test12","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":13,"AccountName":"Test13","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":14,"AccountName":"Test14","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":15,"AccountName":"Test15","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":16,"AccountName":"Test16","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":17,"AccountName":"Test17","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":18,"AccountName":"Test18","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":19,"AccountName":"Test19","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90},{"AccountNumber":20,"AccountName":"Test20","AccountDate":"\/Date(1307641088551)\/","AccountType":"chk","AccountBalance":12345678.90}],"TotalRecordsCount":1000}

[Infragistics] Murtaza Abdeali
on Thu, Jun 9 2011 3:56 PM

hmmm.. can you shoot over a sample you me? murtazaa@infragistics.com

We'll take a deeper look into this. Could be the environment, as you said running on the Dev box is ok.

Thanks,

Taz.

[Infragistics] Angel Todorov
on Mon, Jun 13 2011 3:56 AM

Hi,

JSON is undefined is usually given when you run the page on IE7, and the a JSON library is not loaded. IE7 does not support native JSON, so it requires a compatible JSON parsing library to be loaded. Here is one example of such:

raw.github.com/.../json2.js

Hope it helps. Thanks,

Angel

faltujesi
on Mon, Aug 15 2011 2:09 AM

How can I add reference to Infragistics.Web.Mvc

faltujesi
on Mon, Aug 15 2011 2:12 AM

How can I add reference to Infragististics.Web.Mvc

tech9
on Wed, Dec 7 2011 2:29 PM

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0246: The type or namespace name 'Infragistics' could not be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 1:  @using Infragistics.Web.Mvc;

Line 2:  @{

Line 3:      ViewBag.Title = "Home Page";

tech9
on Wed, Dec 7 2011 2:30 PM

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0246: The type or namespace name 'Infragistics' could not be found (are you missing a using directive or an assembly reference?)

Source Error:

Line 1:  @using Infragistics.Web.Mvc;

Line 2:  @{

Line 3:      ViewBag.Title = "Home Page";

Turntwo
on Sun, Dec 18 2011 11:52 PM

I'm getting the same issues as tech9 - anyone have a solution?

Turntwo
on Sun, Dec 18 2011 11:59 PM

Found the answer posted here:

community.infragistics.com/.../320114.aspx

Basically need to set Infragistics.Web.Mvc to CopyLocal.

vaishalibharat
on Thu, Jan 5 2012 5:00 PM

I get the same error Message: The remote request to fetch data has failed:

when I run your code.

Suresh A
on Mon, Jan 9 2012 11:08 AM

I am getting javascript error

Microsoft JScript runtime error: '$' is undefined

Is there anything which i need to do with the Javascript.

Pls let me know

Regards,

Suresh A

Suresh A
on Mon, Jan 9 2012 11:09 AM

I am getting javascript error

Microsoft JScript runtime error: '$' is undefined

Is there anything which i need to do with the Javascript.

Pls let me know

Regards,

Suresh A

Suresh A
on Wed, Jan 11 2012 8:19 AM

Hi is there any update on this issue. Am also getting the below error

Microsoft JScript runtime error: The remote request to fetch data has failed:  (parsererror) 'JSON' is undefined

Suresh A
on Thu, Jan 12 2012 12:34 AM

Finally i reolved the issue. If we set the webbrowser in compatability mode am getting the below error

Microsoft JScript runtime error: The remote request to fetch data has failed:  (parsererror) 'JSON' is undefined

If i remove the compatibility mode settings then i am not getting any error.

This is an issue in the JQuery grid itself with the jquery.ui.min.js file.

Musings from Rob Richard
on Fri, Jan 13 2012 10:43 AM

Introduction Recently I had occasion to work with a customer developing an MVC application using VB.NET

ognyandim
on Thu, May 31 2012 9:43 AM

This is not working with 2012.1

Please provide some examples with 2012.1 and especially with ig.loader().

ddally
on Mon, Jul 30 2012 3:05 PM

I have tried this and can not seem to get it to work with NetAdvantage 2012.1.  There seems to be an issue with the Bundling.  If I use the example bundle I get an error that jQuery is undefined.  If I change my bundle to include all the jQuery information it gets closer to working but fails with

he remote request to fetch data has failed:  (parsererror) Cannot read property 'paging' of undefined

The lines in bundleConfig below almost work

        bundles.Add(new ScriptBundle("~/bundles/infragistics.loader").Include(

            "~/Scripts/jquery-1.*",

            "~/Scripts/jquery-ui*",

            "~/Scripts/jquery.unobtrusive*",

            "~/Scripts/jquery.validate*",

            "~/Scripts/Infragistics/js/infragistics.loader*"));

stefan michev
on Tue, Nov 27 2012 8:53 PM

after download and compile i'm getting following error:

The view 'CustomerList' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...

My environment: Win7 64b., VS 2010

Thanks in advance

Add a Comment

Please Login or Register to add a comment.