This blog shows how to use Webgrid in ASP.NET MVC. It displays model data in WebGrid in PartialView on selection change of Listbox value.
For this tutorial, you will create a view with ListBox. Listbox will have a list of categories from the Northwind database. On the selection of a category, products under the selected category will be shown in Webgrid. This loads PartialView using jQuery to display Webgrid.
Create a new MVC application with a basic template using Visual Studio.
Open HomeController and add Action Method to show index view,
Create a simple view, name it as an index with Listbox having category names filled into it. You can go through ListBox in the MVC tutorial or you can download source code to get ListBox filled with Categories.
This generates below output.
Right click on the Models folder and add Product.cs. It works as a model for PartialView.
Add below model properties into Product.cs
public string ProductID { get; set; } public string ProductName { get; set; } public string CategoryID { get; set; } public string QuantityPerUnit { get; set; } public string UnitPrice { get; set; } public string UnitsInStock { get; set; } public string ReorderLevel { get; set; }
Open HomeController to add Action Method which accepts CategoryID as input parameter, get data from database according to CategoryID, prepare model and return PartialViewResult with Product model.
Add below Action method code to HomeController.
public PartialViewResult ShowProducts(string categoryID) { IEnumerable<Product> products = GetProducts(categoryID); return PartialView("_showProducts", products); } private IEnumerable<Product> GetProducts(string categoryID) { List<Product> lstProducts = new List<Product>(); string query = string.Format("SELECT [ProductID], [ProductName], " + " [QuantityPerUnit], [UnitPrice],[UnitsInStock], " + " [ReorderLevel] FROM [Northwind].[dbo].[Products] " + " WHERE CategoryID = {0} ", categoryID); " using (SqlConnection con = new SqlConnection("your connection string")) { using (SqlCommand cmd = new SqlCommand(query, con)) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { lstProducts.Add( new Product { ProductID = reader.GetValue(0).ToString(), ProductName = reader.GetString(1), QuantityPerUnit = reader.GetValue(2).ToString(), UnitPrice = reader.GetValue(3).ToString().ToString(), UnitsInStock = reader.GetValue(4).ToString(), ReorderLevel = reader.GetValue(5).ToString() } ); } } } return lstProducts.AsEnumerable(); }
For simplicity I used ADO.NET code to get product details, you may use Entity Framework
In this step you will add a Partial View, which displays Product details in WebGrid.
Add a Partial View with name _showProducts in Views -> Shared folder.
Add below code in _showProducts.cshtml partial view.
@{ ViewBag.Title = "ShowProducts"; Layout = "~/Views/Shared/_Layout.cshtml"; } @model IEnumerable<MvcWebGridExample.Models.Product> @using System.Web.Helpers; <h4>Products</h4> <div id="grid"> @{ var grid = new System.Web.Helpers.WebGrid(Model, rowsPerPage: 5, defaultSort: "ProductName"); } @grid.GetHtml(tableStyle: "webgrid", headerStyle: "header", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("ProductID", "ID", canSort: true), grid.Column(columnName: "ProductName", header: "ProductName", format: item => Html.ActionLink((string)item.ProductName, "Details", "Product", new { id = item.ProductID }, null), canSort: false), grid.Column("QuantityPerUnit", "Qty Per Unit", canSort: false), grid.Column("UnitPrice", "Unit Price", canSort: false), grid.Column("UnitsInStock", header: "Units In Stock", format: item => item.UnitsInStock, canSort: false), grid.Column("ReorderLevel", "Reorder Level", canSort: false) ) ) </div>
We have used Web.Helpers.WebGrid object to display grid style data in MVC. You can have text columns as well as columns with formatted values. In this code ProductName is a link column clicking on it, will redirect to other Route.
For paging, we used rowsPerPage property of WebGrid object and for sorting you can use canSort property of the column.
For styling of each row, and alternate row you can use below css.
.webgrid { margin: 4px; border-collapse: collapse; width: 90%; } .header { padding: 6px 5px; text-align: center; background-color: #e8eef4; border-bottom: 2px solid #3966A2; height: 40px; font-weight: bold; border-top: 2px solid #D6E8FF; border-left: 2px solid #D6E8FF; border-right: 2px solid #D6E8FF; } .webgrid th, .webgrid td { border: 1px solid #C0C0C0; padding: 5px; } .alt { background-color: #E8E8E8; color: #000; } .product { width: 50px; font-weight: bold; }
In this step, you will load _showProducts partial view using jQuery. We already have added the Action method which returns PartialViewResult in HomeController.
Open Index.cshtml and add below scripts
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"> </script> <script> $(document).ready(function () { --code to load categories to Listbox $.getJSON('home/GetCategoriesWithModel/', function (data) { //clear the current content of the select $('#Categories').empty(); //iterate over the data and append a select option $.each(data, function (i, item) { $('#Categories').append('<option value="' + item.CategoryID +'">' + item.CategoryName + '</option>'); }) }); --code to load _showProducts PartialView with --Product details of selected category into WebGrid $('#Categories').change(function () { $("#products").load('/home/ShowProducts', { categoryID: $(this).attr('value') }); }); }); </script>
Now execute your application and navigate to home page. This displays a ListBox filled with categories, click on any category corresponding products will load in WebGrid PartialView.
It generates below output.
You may want to display selected row with different style. You can use below css to decorate selected row on mouse hover.
.clickable { cursor: pointer; background: #ffff99; }
While using WebGrid, you may get compile time error CS0234: The type or namespace name 'WebGrid' does not exist in the namespace 'System.Web.Helpers' (are you missing an assembly reference?).
To remove this compile time error follow below steps
Add reference to System.Web.Helpers library.
In view where you are using Webgrid add @using System.Web.Helpers;.
In Web.config add assembly System.Web.Helpers. Your config will looks like.
<assemblies> <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies>
Nice Post
Thank you for your sharing information
Great information. Since last week, I am gathering details about asp experience. There are some amazing details on your blog which I didn’t know. Thanks.I am gonna implement it.