• How to Display our Database Data in WebGrid in MVC

    by  • January 13, 2016 • Microsoft ADO.NET, Microsoft ASP.NET MVC, Microsoft SQL Server • 0 Comments

    In the previous article, we save the data submitted by the user in a SQL database. Here we will learn, how to display that SQL data in Grid View. Grid View displays data in tabular form. To display our data in a grid, we use WebGrid class in ASP.NET. WebGrid is one of the many useful ASP.NET Web helpers. Here at first we have to create a database and add ADO.NET entity model before displaying data in the Grid format. You have to read my previous articles to go through database creation and adding ADO.NET model.

    Now first of all we will look at the BooksController.cs code, that’s given below

    In the above code, we are creating instance of our database new keyword followed by store() constructor. Then we use ToList() method to get the List view of the Book database stored in SQL and passing that list to the view View(books).

    Now lets look at the Index View code given below

    In the above code, we use WebGrid class and WebGrid helper methods to display our data in Grid View by WebGrid grid = new WebGrid().WebGrid helper method simplifies the way to display the data. This helper method automatically set up an HTML Table. We can sort the data, can do paging  and format the data through this helper.

    Then we use grid. Pager() method, that provides us the specified paging support for grid view. WebGridPagerModes.all/numeric/FirstAll  parameter specifies the flag which provides us the methods for moving between the pages. Then we use style tag to specify the css for our grid view.

    Then we use grid.GetHtml() method that is used to render a specified Html attribute. In our database we have four columns and we are rendering that columns by using grid.GetHtml() method. We are also rendering the css styles.

    When we run our program, we will see the following Grid View of our database.

    outputnew




    Namecheap.com

    Leave a Reply