WebGrid Example In ASP.NET MVC


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 Northwind database. On selection of category, products under selected category will be shown in Webgrid. It loads partialview using jQuery to display Webgrid.


  1. Create a new MVC application with basic template using Visual Studio.

    Open HomeController and add Action Method to show index view,

    Create a simple view, name it as index with Listbox having category names filled into it. You can go through ListBox in MVC tutorial or you can download source code to get ListBox filled with Categories.

    It generates below output.

    Populate MVC ListBox

  2. Right click on Models folder and add Product.cs. It works as 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; }
                

  3. 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.

  4. 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 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 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;
        } 
                

  5. Load PartialView using jQuery

    In this step you will load _showProducts partial view using jQuery. We already have added 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/2.1.4/jquery.min.js">
        </script>
    
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.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. It displays a ListBox filled with categories, click on any category corresponding products will load in WebGrid PartialView.

    It generates below output.

    asp net mvc web grid example


  6. Clickable Row

    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;
    }
                

  7. 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

    1. Add reference to System.Web.Helpers library.

    2. In view where you are using Webgrid add @using System.Web.Helpers;.

    3. 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>
                          

Download source code.

Speak your mind :
Leave a comment for this article on dotnetbloogers.com
User profile picture on dotnetmentors.com

by bestdotnet at 4/19/2017 1:31:00 AM
Nice Post, Please visit our Bestdotnettraining.com/blog you can get some articles on Microsoft technologies
post comment on dotnetmentors.com