How to use WebGrid to display grid in MVC application

webgrid in mvc

For last few weeks I have been working on an ASP.Net MVC application that requires use of grid view kind of user interface. Since the user interface was not very complicated I found that use of WebGrid will do the trick. In this post I will discuss simple use of WebGrid extension in MVC framework.

How to use WebGrid

The following code snippet shows simple use of WebGrid extension.

@model IQueryable<WebGridSamples.Models.Post>
@{
    var grid = new WebGrid(source: Model, 
                           defaultSort: "DateCreated",  
                           rowsPerPage: 25,
                           canSort:true);
}
<div>
    @grid.GetHtml()
</div>
    

As you can see a very simple use of WebGrid requires following.

  1. Define a new instance of WebGrid object
  2. Set data source in source property of WebGrid object. This source is data collection that you intend to display as grid.
  3. And then call GetHtml method on WebGrid object

Controlling behavior of WebGrid display

Displaying data in a grid is not sufficient by itself. If you look at the snapshot of grid in this post, you can see that it is not very intuitive and display itself is not very impressive as well. Therefore it is important that you must be able to control behavior of the grid. As you can see that when I created instance of WebGrid object, I have specified values of some the properties. In this post I have only mentioned four properties, source, defaultSort, rowsPerPage and canSort. The named of these properties itself indicate what this properties are used for. I will discuss these properties in detail in subsequent posts.

Setting source for WebGrid

So far I have only shown how the code looks like on CSHTML page. The most important part of WebGrid use is data collection that we want to display. Following code snippet shows controller side of the code that sets the collection in Model of this view.

public ActionResult Index()
{
    var blogRepository = new BlogRepository
        (ConfigurationManager.ConnectionStrings["blogdb"].ConnectionString);
    var posts= blogRepository.GetAllPosts();
    return View(posts);
}
    

There is nothing very complicated about this code. I have used EntityFramework in my prototype application to pull data from my blog database. And then returned it as IQueryable collection in model of view of the page itself. Following code snippet shows the method that I implemented that uses Entity Framework.

public IQueryable<Post> GetAllPosts()
{
   using (var context = new BlogContext(ConnectionString))
   {
    return context.Posts.ToList().AsQueryable();
   }
}
    

As you can see how easy it is to WebGrid extension to display grid view in MVC application.

Search

Social

Weather

-0.8 °C / 30.6 °F

weather conditions Snow

Monthly Posts

Blog Tags