ASP.NET MVC 3–Working with WebGrid (Part 2)

Introduction

On my previous post I shown how to display simple data using the new WebGrid feature. On this post I’ll continue and show a little bit more how can we configure the WebGrid and customize it.

WebGrid Properties

The WebGrid have a set of properties that allow us to customize it, I’ll cover here only the most common/important ones.

  • Source – Where your data come from. Usually the model passed by the controller action.
  • DefaultSort – Here you can define how the data will be sorted. Just inform the column name here. Example “Id” or “Name”.
  • RowsPerPage – Quantity of records that will be shown on table.
  • CanPage – Allow the paging.
  • CanSort – Allow the sorting by clicking on column title.

Here is an initial sample:

   1: var gridItens = new WebGrid(source: Model,
   2:      defaultSort: "Title",
   3:      rowsPerPage: 15,
   4:      canPage: true,
   5:      canSort: true);

This way we have a WebGrid receiving data from our model (Passed by the action) default sorting by the title with 15 rows per page and with paging and sorting. Easy!

FieldNamePrefix

An important property is the FieldNamePrefix, as you can have multiple WebGrids on the same view. This property allow us to have a prefixed string before the query string parameters. We can better check this feature by checking these two images:

image

Note that we have a parameter called “sort”, but there`s nothing specifying which WebGrid this sort belongs to. If we use the FieldNamePrefix, we can specify it, and now you can clearly see from which WebGrid the sort parameter belongs to:

image

Now we have a prefix before the parameter sort (gridItens_), and this way we can have multiple WebGrids on the same view and the sort or paging of each grid will not affect the other grids.

Here is the code:

   1: var gridItens = new WebGrid(source: Model,
   2:     defaultSort: "Title",
   3:     rowsPerPage: 15,
   4:     canPage: true,
   5:     canSort: true,
   6:     fieldNamePrefix: "gridItens_");

To finish, just take a look at the HTML generated. I highlighted the fieldNamePrefix string defined on this image:

image

PageFieldName

This property is similar to the FieldNamePrefix, but this just work for paging action. In this case the keyword “page” that represents the current grid paging will be replaced by the string you define on this parameter.

Lets take a look on the two next images to better understand how it works:

image
This is a sample without using the PageFieldName, and as we can see, the default parameter is “page”.

image
This is a sample using the PageFieldName and we can see that the parameter “Page” was replaced by “inside”.

The code to do this is here:

   1: var gridItens = new WebGrid(source: Model,
   2:      defaultSort: "Title",
   3:      rowsPerPage: 5,
   4:      canPage: true,
   5:      canSort: true,
   6:      fieldNamePrefix: "gridItens_",
   7:      pageFieldName: "inside");

SelectionFieldName

Similar as the other ones, this parameter allow us to customize the parameter (Passed on the query string) to refer the selected row in the WebGrid. As the effect is the same, I’ll just show the difference between using and not this option.

On this image, we have a fixed string called “row” that tell us which row is selected on the WebGrid. If for any reason you need to change this value, you can just use the SelectionFieldName property to redefine it.

image

The result will be similar to this:

image

And the code to do this is here:

   1: var gridItens = new WebGrid(source: Model,
   2:      defaultSort: "Title",
   3:      rowsPerPage: 5,
   4:      canPage: true,
   5:      canSort: true,
   6:      fieldNamePrefix: "gridItens_",
   7:      pageFieldName: "inside",
   8:      selectionFieldName: "selectedRow");

As the other properties (SortFieldName and SortDirectionFieldName) have the similar usage, I’ll not describe it here. But if you got how to use those above, you’ll be able to use the other ones.

Styling your grid

This is an important part and I have to assume that I liked the ways we have to customize the WebGrid. As I work close to my customer, the appearance of our applications should be light and rich, and I have to confess I was afraid I can’t do it with WebGrid.

I’m happy to say I was wrong =D

The WebGrid have a set of properties that allow us to customize it easily using CSS and following the WebStandards. I just think it could be better if it have an HtmlAttribute option, that we can input some attributes like “Id”, important when we are working with jQuery. But I think it will come on next versions.

So, let’s take a look on the properties to do this customization.

   1: gridItens.GetHtml(
   2:      tableStyle: "webgrid",
   3:      headerStyle: "webgrid-header",
   4:      footerStyle: "webgrid-footer",
   5:      alternatingRowStyle: "webgrid-alternating-row",
   6:      selectedRowStyle: "webgrid-selected-row",
   7:      rowStyle: "webgrid-row-style")

Not that I used a set of properties (Easy to understand) to apply to each one a style. For the entire table I used the tableStyle property, for the table header the tableHeader and etc…

Now, on my CSS file (Content/Site.css) I’ll input the styles for this grid as follow:

   1: .webgrid
   2: {
   3:     width: 50%;
   4:     border: 0px;
   5:     border-collapse: collapse;
   6: }
   7:  
   8: .webgrid a
   9: {
  10:     color: #000;
  11: }
  12:  
  13: .webgrid-header
  14: {
  15:     padding: 6px 5px;
  16:     text-align: center;
  17:     background-color: #e8eef4;
  18:     border-bottom: 2px solid #3966A2;
  19:     height: 40px;
  20:  
  21:     border-top: 2px solid #D6E8FF;
  22:     border-left: 2px solid #D6E8FF;
  23:     border-right: 2px solid #D6E8FF;
  24: }
  25:  
  26: .webgrid-footer
  27: {
  28:     padding: 6px 5px;
  29:     text-align: center;
  30:     background-color: #e8eef4;
  31:     border-top: 2px solid #3966A2;
  32:     height: 30px;
  33:  
  34:     border-bottom: 2px solid #D6E8FF;
  35:     border-left: 2px solid #D6E8FF;
  36:     border-right: 2px solid #D6E8FF;
  37: }
  38:  
  39: .webgrid-alternating-row
  40: {
  41:     height: 30px;
  42:     background-color: #f2f2f2;
  43:     border-bottom: 1px solid #d2d2d2;
  44:  
  45:     border-left: 2px solid #D6E8FF;
  46:     border-right: 2px solid #D6E8FF;
  47: }
  48:  
  49: .webgrid-row-style
  50: {
  51:     height: 30px;
  52:     border-bottom: 1px solid #d2d2d2;
  53:  
  54:     border-left: 2px solid #D6E8FF;
  55:     border-right: 2px solid #D6E8FF;
  56: }
  57:  
  58: .webgrid-selected-row
  59: {
  60:     font-weight: bold;
  61: }

The final result is it:

image

Customizing Columns

As you could see on the previous image, my columns are in a different language (Portuguese – Brazil), so let’s check how I did that.

On the WebGrid, we have a property called Columns that receive a list of Column. Here we will customize the grid columns.

The following code shows how to create columns on the WebGrid:

   1: columns: gridItens.Columns(
   2:  
   3:      gridItens.Column(
   4:          columnName: "Title",
   5:          header: "Título",
   6:          style: "text-align-left"),
   7:  
   8:      gridItens.Column(
   9:          columnName: "Price",
  10:          header: "Preço",
  11:          style: "text-align-center",
  12:          format: (item) => string.Format("{0:C}", item.Price)),
  13:  
  14:     gridItens.Column(
  15:          columnName: "Quantity",
  16:          header: "Qtd em Estoque",
  17:          style: "text-align-center")
  18:  )

We have four options here and they are:

  • columnName – Used to know which member of our model will be displayed. Price, Name, Id, etc…
  • header – The text that will be displayed on the column header.
  • style – CSS style of the column. In this example, you can see that for some columns I want they text aligned to center, so I applied the “text-align-center” style to them.
  • format – Used to format the displayed string.

Just to better understand the format property, here is how it was displayed after use the format “{0:C}” (For currency).

image

 

Selecting a row

Yes, we can select a row using the WebGrid and manipulate the data =D

To do this, we need to include an “special” column and use the method GetSelectItem([optional]string text) which allow us to get the row selected. If we simply call this method we will have the default text “Select”, but it can be changed by simply informing a string when call the method like GetSelectedItem(“[ + ]”) or GetSelectedItem(“Details”).

We can also use a column from our model by informing the property to be shown like this GetSelectLink(item.Title).

Here is the base code to do this and some variants.

   1: columns: grid.Columns(
   2:     grid.Column(
   3:         header:"",
   4:         style: "text-align-center",
   5:         format:(item) => item.GetSelectLink(item.Title)),
   6:  
   7:     grid.Column(
   8:         header: "",
   9:         style: "text-align-center",
  10:         format: (item) => item.GetSelectLink("Custom Text")),
  11:  
  12:     grid.Column(
  13:         header: "",
  14:         style: "text-align-center",
  15:         format: (item) => item.GetSelectLink()),  

And the result is here:

image

And here is a sample of a selected row:

image

With the row selected, now we start a process to read its data.

Note that this is only a way to do this, and may not be the most performatively way to do this.

Here is the code to get the value from a selected row and capture the item:

   1: CustomWebGrid.Models.Product product = new CustomWebGrid.Models.Product();
   2: if (gridItens.HasSelection)
   3: {
   4:     product = (CustomWebGrid.Models.Product)gridItens.Rows[gridItens.SelectedIndex].Value;
   5: }
   6: else
   7: {
   8:     product = (CustomWebGrid.Models.Product)gridItens.Rows[0].Value;
   9: }

Note that the grid returns an object (In this case a product), and with this information we can display the details of the product easily, or manipulate the data as you want.

   1: <b>Title:</b> < %: product.Title % ><br />
   2: <b>Price:</b> < %: product.Price % ><br />
   3: <b>Quantity:</b> < %: product.Quantity % ><br />
   4: <br />

Here is the final result:

image

Note that I displayed the amount of records found also =)
I did it using the property “gridItens.TotalRowCount”.

It’s simple, it’s easy, it’s light, it’s ASP.NET MVC =D

 

André Baltieri
MSN:
andrebaltieri@hotmail.com | Twitter: @andrebaltieri
Blog: http://weblogs.asp.net/andrebaltieri

Inside .NET Users Group Leader
http://www.insidedotnet.com.br/

Published Tuesday, November 02, 2010 7:32 PM by andrebaltieri

Comments

# Twitter Trackbacks for ASP.NET MVC 3???Working with WebGrid (Part 2) - Andre Baltieri - ASP.NET MVC [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 ASP.NET MVC 3???Working with WebGrid (Part 2) - Andre Baltieri - ASP.NET MVC         [asp.net]        on Topsy.com

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Friday, November 12, 2010 4:43 PM by Nairb

This is nice, but is there any way to do the paging manually/on the server? If not, then this is essentially useless for all but trivial apps.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Sunday, November 14, 2010 10:51 AM by andrebaltieri

Hi Narib, you can use the Skip and Take features of ADO.NET Entity Framework to limit the quantity of records passed to the view, this way you can page the records.

Here is an example:

return View((from r in context.Records where ... select r).Skip(10).Take(10));

or just

return View(context.Records.Skip(10).Take(10));

regards,

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Thursday, January 13, 2011 6:00 PM by Perry

You cannot implement skip take without breaking paging as the grid has to know how many records it will have. You have to return all the records or do manual paging.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Tuesday, February 15, 2011 4:15 AM by satheesh.manian

Hi,

Good sample.

I have below requirement.

I need to place 'Edit','Show' buttons in last two columns.

If i Click 'Edit' button, i need to show the record in Textboxes(should be in same page), If i Click 'Show', i need to show the record in Labels(also in same page).

How can i achieve the same.

Kindly appreciating your help.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Tuesday, February 15, 2011 7:54 AM by andrebaltieri

satheesh.manian, I`m not sure we have this kind of feature on this version of WebGrid.

For the buttons, you can use item.GetSelectLink to get the item Id and format it as a link, but for the edit in row function I have no idea how to create it.

You can try other grids as jGrid for jQuery, maybe these can work for your scenario.

Remember that if need a lot of "magical" things like this you mentioned, maybe ASP.NET Web Forms works best, using a GridView.

Thanks and regards,

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Friday, March 04, 2011 5:46 AM by Ian McInnes

How does it handle large amounts of data, say a list of all current accounts held by a bank. Is there a way to intercept sort/page events to resource data via Ajax from the server?

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Monday, March 28, 2011 9:39 PM by Monski

Hi how about, a display message on the grid that the search contains no record found... web grid just got empty if no records found on my query,,, can you help me about this.

cheers

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Tuesday, March 29, 2011 5:27 AM by Ajit Kumar Subudhi

Hi Can you please provide the code how to write the below code on razor page:

1: CustomWebGrid.Models.Product product = new CustomWebGrid.Models.Product();

 2: if (gridItens.HasSelection)  

3: {  

4:     product = (CustomWebGrid.Models.Product)gridItens.Rows[gridItens.SelectedIndex].Value;   5:

}  

6: else  

7: {  

8:     product = (CustomWebGrid.Models.Product)gridItens.Rows[0].Value;  

9: }

--------

1: <b>Title:</b> < %: product.Title % ><br />   2: <b>Price:</b> < %: product.Price % ><br />   3: <b>Quantity:</b> < %: product.Quantity % ><br />   4: <br />

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Friday, July 15, 2011 8:43 AM by Aamir Saeed

@{

   CustomWebGrid.Models.Product selectedproduct = null;

   if(grid.HasSelection) {        

       selectedproduct = (CustomWebGrid.Models.Product)grid.Rows[grid.SelectedIndex].Value;

   }

   else {

       selectedproduct = (CustomWebGrid.Models.Product)grid.Rows[0].Value;

   }

}

<div>Customer First Name:</div>

<div>@selectedproduct.Title</div>

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Thursday, August 25, 2011 8:12 PM by Tore Aurstad

Very informative and helpful presentation of the WebGrid in ASP.NET Mvc 3.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Tuesday, September 06, 2011 12:41 PM by Alex

good article on MSDN

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Monday, September 26, 2011 5:49 AM by govind kumar

Hi Aamir,

How can we load WebGrid(Child grid) on ["+"] or "select".

Basically, i want to impliment Parent-Child(Nested WebGrid) with expend/collaps option.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Friday, October 07, 2011 10:56 AM by Nice article but a question about table headers in padding

I am playing around with styling the grid and I cannot seem to affect the padding in the header cells. I have checked the result in IE8 and chrome. I even tried your header style above and it doesn't actually change the padding.

I am using this code currently:

.TallyTableHeader

{

 padding: 3px;

 background-color: dodgerblue;

 font-weight: 700;

 color: White;

 text-align: left;

}

and I specify it in my grid code:

@grid.GetHtml(

< other param values >

       headerStyle: "TallyTableHeader",

       displayHeader: true

);

The only way I have seem to be able to affect the padding in the header is to specify a style sheet for th elements.

# re: ASP.NET MVC 3–Working with WebGrid (Part 2)

Wednesday, October 12, 2011 12:20 PM by bflow1

Thanks A Milliion! I had a similar problem with two grids in the view. I would select a row from one grid, and the HasSelection property would be set for both. which caused the code for both to execute. Painful to figure out.

# Crear un GridView en Asp.Net MVC3 (WebGrid) - Como crear una web

Pingback from  Crear un GridView en Asp.Net MVC3 (WebGrid) - Como crear una web

Leave a Comment

(required) 
(required) 
(optional)
(required)