WebGrid WebHelper in ASP.NET MVC 3 RC

Posted by: Malcolm Sheridan , on 12/3/2010, in Category ASP.NET MVC
Views: 146495
Abstract: The following article demonstrates how to use the WebGrid web helper in ASP.NET MVC 3 RC

ASP.NET MVC 3 RC contains a full suite of web helpers that Microsoft have made available through the Microsoft Web Helpers library. This can be downloaded through NuGet (formerly NuPack). NuGet is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. One web helper that could reduce the amount of code you need to write is the WebGrid web helper. As the name suggests, this web helper takes a collection of data and renders a HTML table. This article will show you how to download the library and start using this web helper. This code also works in WebMatrix if you're using it.

Update: You can also read Part-II of this article Efficient Paging with WebGrid Web Helper - ASP.NET MVC 3 RC

Before moving on, you need to download ASP.NET MVC 3 RC. Click here to download and install them using the Microsoft Web Platform Installer.

The Microsoft Web Helpers are added as a reference by default now in ASP.NET MVC 3 RC. I’ve left the instructions on how to add them in this article in case you need to do this as a separate exercise.

Open visual studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. The new MVC 3 dialog can be seen below:

MVC Empty Template Razor

Choose Razor as the view engine and click OK.

The next step is to download the Microsoft Web Helpers library through NuGet. Follow these steps to do this:

Step 1: Right click the website and choose Add Package Reference.

Mvc Add Package Reference

2. The Add Package Reference dialog will open. Search for Microsoft in the search box in the top right corner. Upon completion you'll see microsoft-web-helpers option. Select that option and click Install.

Microsoft Web Helpers


3. Click Close to return to the project

Check the references and you'll see that the library has been added to the project.

System Web Helpers

Now it's time to start coding! To start using the WebGrid web helper, start off by creating an object reference to the WebGrid class:

Mvc WebGrid


The WebGrid constructor takes a number of parameters. Only one is mandatory. Here’s an explanation of all of them:

System.Collections.Generic.IEnumerable<dynamic> source
The collection of objects

System.Collections.Generic.IEnumerable<string> columnNames = null
The names of the columns appearing in the grid

string defaultSort = null
The name of the column to sort the grid by default

int rowsPerPage = 10
The number of rows to display per page is paging is enabled

bool canPage = true
Determines if the WebGrid can be paged

bool canSort = true
Determines if the WebGrid can be sorted

string ajaxUpdateContainerId = null
The id of the containing element for Ajax paging and sorting support

string ajaxUpdateCallback = null
The callback function for Ajax paging and sorting support

string fieldNamePrefix = null
The value which prefixes the default querystring fields

string pageFieldName = null
A value that replaces the default querystring page field

string selectionFieldName = null
A value that replaces the default querystring row field

string sortFieldName = null
A value that replaces the default querystring sort field

string sortDirectionFieldName = null
A value that replaces the default querystring sortdir field

The GetHtml method renders the grid. To render a simple grid with no formatting, use the following code. I’m using the model that’s being passed in to the view for these examples.

Mvc WebGrid Model


Styling the ASP.NET MVC 3 WebGrid

To make the grid more visually appealing, you can customise each column. One of the optional arguments GetHtml accepts is columns, which is a collection of WebGridColumn objects.

Mvc WebGrid Column

Taking this one step further, you can attach css class attributes to the WebGrid. This abstracts the styling from the generated HTML. GetHtml allows you to specify a table, header and alternating row style. See below.

Mvc WebGrid Css


Paging the ASP.NET MVC 3 WebGrid

To make the UI experience even better, the WebGrid also has built-in paging. To enable paging, you can customise the Pager object that’s associated to the grid.
Mvc WebGrid Paging

One caveat before using the paging is that all the data is fetched upon each page request. This is fine if you’re working with a small set of data, but if you have thousands of records, performance would degrade dramatically. I’ll show you in my next article on how to deal with this.

Update: You can now read Part-II of this article Efficient Paging with WebGrid Web Helper - ASP.NET MVC 3 RC

The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Jon on Friday, December 3, 2010 3:58 AM
Interesting stuff. Looking forward to your next article about improving paging performance. Hope there is some AJAX examples too!
Comment posted by Malcolm Sheridan on Saturday, December 4, 2010 5:17 PM
@Jon
I'm glad you liked the article.  I'm getting the next one on paging sorted out now.
Comment posted by Jon on Tuesday, December 7, 2010 5:34 AM
I'd also like to see if possible a comparison of MVC grids as I know there are a few. Thanks
Comment posted by Malcolm Sheridan on Tuesday, December 7, 2010 6:55 AM
@Jon
Great idea!  I'll look into it.
Comment posted by Jorge on Tuesday, December 7, 2010 10:29 PM
This is very close to what I was looking for. Did you write the article on paging performance? I am eager to read it.
Comment posted by Malcolm Sheridan on Wednesday, December 8, 2010 4:38 AM
@Jorge
Yes and it should be available this week.  Keep an eye out for it.
Comment posted by Tom on Wednesday, December 8, 2010 12:02 PM
How change theme in MVC Razor (ViewEngineTheme  or some other way. )
Comment posted by Tom on Wednesday, December 8, 2010 12:05 PM
How change theme in MVC Razor (ViewEngineTheme  or some other way. )
Comment posted by shawn z on Tuesday, August 2, 2011 12:22 PM
Cutting and pasting that does not work in MVC3. To get the extension to work, I had to create a class file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace incMvcSite.Classes {
    public static class HtmlPrefixScopeExtensions {
        public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) {
            return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
        }

        private class HtmlFieldPrefixScope : IDisposable {
            private readonly TemplateInfo templateInfo;
            private readonly string previousHtmlFieldPrefix;

            public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) {
                this.templateInfo = templateInfo;

                previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
                templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
            }

            public void Dispose() {
                templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
            }
        }
    }
}
In the Razor (.cshtml) file, I added the following:
@using incMvcSite.Classes
@using(Html.BeginHtmlFieldPrefixScope("Permission")) {
    
        Permission

        // The Html.EditorFor's would go here...
    
}
Notice the using to bring me extension class into scope. That allows the second using line to work.
Now the problem is that when posting back, the object is not updated. In my controller, I used a second parameter to specify my prefix:
TryUpdateModel(modelUser.Permission, "Permission");
This added the prefix to all field in the HTML, and the TryUpdateModel loaded the object with prefixed control names. Now you can properly namespace your controls for embedded edit lists, and for partial views of models with the same property names.

Shawn Zernik
Internetwork Consulting
http://www.internetworkconsulting.net
Comment posted by Martin on Wednesday, August 3, 2011 10:02 PM
Thanks shawn!
Comment posted by Vijay on Monday, September 12, 2011 5:05 PM
How we can make WebGrid editable
Comment posted by AD on Friday, January 27, 2012 12:52 AM
Great article, very useful for beginners
Comment posted by mcartur on Thursday, May 17, 2012 12:42 PM
Thanks¡¡ You save me time¡
Comment posted by anand on Wednesday, May 23, 2012 4:49 AM
Thanks for a good article.
Comment posted by Nick Yates on Wednesday, July 3, 2013 7:31 PM
Great stuff, I don't know why there's so few articles about WebGrid around.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel