1. Back To Blog

ASP.NET MVC interview questions: - What is WebGrid in MVC and how to use it?

WebGrid is a helper introduced in MVC 4 which will let us render tabular data in a very simple manner. It has inbuilt support for sorting, paging, asynchronous updates via ajax and custom column formatting.


Following are the steps to implement WebGrid.


Step 1 - Create Model Data


First we need data which we will use to bind webgrid. We may get this as a model or may be as ViewData. In our case we assume that we will get as Model.




Step 2 - Make your view a strongly typed view


@model List


Step 3 - Create instance of WebGrid


WebGridMyGrid = new WebGrid(Model);


Write following code in your view,


Step 4-Render Grid


Write following code in your view,


@grid.GetHtml()


Output


CustomerId

CustomerName

CustomerAddress

1

A

AA

2

B

BB

3

C

CC


Customizing WebGrid


  • Paging - For that we will use overloaded version of webgrid constructor as follows,


WebGridMyGrid = new WebGrid(Model, rowsPerPage:3);


Output (considering we have total 10 records in the model)



CustomerId

CustomerName

CustomerAddress

1

A

AA

2

B

BB

3

C

CC

1 2 3 4 >


  • Customize columns - We will use overloaded version of GetHtml Method for that as follows,


@grid.GetHtml

(

            columns:grid.Columns

            (

                        grid.Column("CustomerId", "Customer Id"),

                        grid.Column("CustomerName", "Customer Name"),

                        grid.Column("CustomerAddress", "CustomerAddress")

            )

)


Output


CustomerId

CustomerName

CustomerAddress

1

A

AA

2

B

BB

3

C

CC


Hope you enjoyed reading this and learned something new. Your comments and votes are always welcome.


If you are looking for some hard core live training on MVC, WCF, Design Patterns, BI, WPF, TFS, HTML5 visit www.sukesh-Marla.com or contact SukeshMarla@Gmail.com.


Also see following ASP.NET MVC interview questions video on MVC Asynch controllers and thread starvation: -



You can also read this article which talks in details about MVC WebGrid from here

http://www.codeproject.com/Articles/843788/WebGrid-in-ASP-NET-MVC-important-tips

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social