Thursday 4 July 2013

WebGrid in ASP.NET MVC



We can define WebGrid as displays data on a web page using an HTML table element. It renders tabular data in a very simple manner with support for custom formatting of columns, paging, sorting and asynchronous updates via AJAX.
The main properties in webgrid are:
    Source – Where your data come from. Usually the model passed by the controller action.
    DefaultSort – Here you can define how the data will be sorted. Just inform the column name here.
    RowsPerPage – Quantity of records that will be shown on table.
    CanPage – Allow the paging.
    CanSort – Allow the sorting by clicking on column title.
 SelectedFieldName-Gets the full name of the query-string field that is used to specify the selected row of the WebGrid instance.
In this article I am explaining how to use WebGrid in asp .net mvc 4 application.First I am going to create a Model  name as Product. 

Product.cs 

public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long Quantity { get; set; }
    }



I am using  Razor view engine and My  InventoryController contain following action: 
InventoryController.cs

public ActionResult WebgridSample()
        {
       ObservableCollection<Product> inventoryList = new    ObservableCollection<Product>();
            inventoryList.Add(new Product { Id = "P101", Name = "Computer", Description = "All type of computers", Quantity = 800 });
            inventoryList.Add(new Product { Id = "P102", Name = "Laptop", Description = "All models of Laptops", Quantity = 500 });
            inventoryList.Add(new Product { Id = "P103", Name = "Camera", Description = "Hd  cameras", Quantity = 300 });
            inventoryList.Add(new Product { Id = "P104", Name = "Mobile", Description = "All Smartphones", Quantity = 450 });
            inventoryList.Add(new Product { Id = "P105", Name = "Notepad", Description = "All branded of notepads", Quantity = 670 });
            inventoryList.Add(new Product { Id = "P106", Name = "Harddisk", Description = "All type of Harddisk", Quantity = 1200 });
            inventoryList.Add(new Product { Id = "P107", Name = "PenDrive", Description = "All type of Pendrive", Quantity = 370 });
            return View(inventoryList);
        }




In my  WebgridSample View I am creating a webgrid and  specify the columns in the call to GetHtml. 

WebgridSample.cshtml:


 @{
    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName:  "selectedRow",ajaxUpdateContainerId: "gridContent");    grid.Pager(WebGridPagerModes.NextPrevious);}




WebGrid helper allows us to add a class names to style the table, header, footer, row and alternating row elements.


<style type="text/css">
        .webGrid { margin: 4px; border-collapse: collapse; width: 500pxbackground-color:#FCFCFC;}
        .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
        .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
        .alt { background-color: #E4E9F5; color: #000; }
        .gridHead a:hover {text-decoration:underline;}
        .description { width:auto}
        .select{background-color: #389DF5}
    </style>

Adding the columns to grid for specifying the column order  ,name and field to bind.

<div id="gridContent">
        @grid.GetHtml(tableStyle: "webGrid",
                headerStyle: "header",
                alternatingRowStyle: "alt",
                selectedRowStyle: "select",
                columns: grid.Columns(
                grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)),
                grid.Column("Name", " Name"),
                grid.Column("Description", "Description", style: "description"),
                grid.Column("Quantity", "Quantity")
         ))
</div>


For navigating the selected item I used format parameter in Id column. The format parameter of the Column method allows us to customize the rendering of a data item.


grid.Column("Id", format: (item) => item.GetSelectLink(item.Id))     


The below code display the selected row in a html code block, and for that I created a instance of the  model Product.

@{
    InventoryManagement.Models.Product product = new InventoryManagement.Models.Product();
    }
          @if (grid.HasSelection)
         {
             product = (InventoryManagement.Models.Product)grid.Rows[grid.SelectedIndex].Value;
             <b>Id</b> @product.Id<br />
             <b>Name</b>  @product.Name<br />
             <b>Description</b> @product.Description<br />
             <b>Quantity</b> @product.Quantity<br />
 }



 For avoiding page refresh while pagination we can add ajax  parameter  ajaxUpdateContainerId and wrap the grid markup with a DIV element. Here we can assign the div id as  ajaxUpdateContainerId . 

 ajaxUpdateContainerId: "gridContent"

 Add a reference to jquery .



<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>



If you want to select one item from webgrid and want to show it in a separate page, you can use action link in particular grid column. So when you select the item the selected item will pass to the action which will redirect to the page by retrieving with corresponding record.In mcv we can see @html.ActionLink for redirect to action.
The parameter using in actionlink are linktext,action name,controller name,route value, html arguments.

grid.Column("Detail", format: @<text>@Html.ActionLink("Select", "Submit",
                new { QtId = item.QtId }) </text>),
 


15 comments:

  1. Really Appreciated..Good Job.

    ReplyDelete
  2. I have downloaded the code and it working fine.
    Now I want to have the webgrid in my project.
    THe code have the reference to System.Web.Helper dll that contains Webgrid but when I am writing

    @{ var grid= new WebGrid(...)
    It is not identifying the WebGrid saying reference missing

    Any suggestion?>

    ReplyDelete
  3. good job
    post more article on mvc

    ReplyDelete
  4. Solved a problem I was fighting. Thanks so much, great walktrhough.

    ReplyDelete
  5. decent example, but I am disappointed in the rampant use of the submit style of buttons... what good is partial View if you have to submit the page? I hardly ever want to submit the page in my web applications, but these are the majority of examples out there... Most of the time I want to see section B of my web page after I've made some selection and clicked a button in section A. Where's that example. I get these are simplistic approaches for the novice but some of us are seasoned programmers trying to grasp the complete set of possibilities of MVC features and its tough to do when all I get are examples for novices, but in the real world of web development... you seldom want to submit the page or am I missing something... not trying to insult but just a frustrated observation

    ReplyDelete
  6. Generally Project Management Tools are available as desktop applications, hosted software and online web based software. Many Project manager prefer desktop applications, but the major drawback is that only one user can be used at a time.
    online store

    ReplyDelete
  7. Had to add using System.Collections.ObjectModel; Now I get:
    Error 1 The type or namespace name 'Product' could not be found (are you missing a using directive or an assembly reference?)

    if I add using InventoryManagement.Models; I get

    Error 1 Cannot implicitly convert type 'InventoryManagement.Models.Product' to 'System.Collections.ObjectModel.ObservableCollection'

    Any help?

    ReplyDelete
  8. hello,Mr RANO , i need the exact code in vbhtml , will u please provide me also i should brig the data using web grid from the table of db i m strugling with this for last 1 week

    thanks in advance
    Velsamy

    ReplyDelete
  9. how to take column variable in jquery

    ReplyDelete
  10. who is the sob dumb shit face who post this worthless piece of crap
    this article sucks that fucking nigger dick
    notice there is dropdown box to edit
    or comb box box or checkbox
    who ever posted this article has his unit inch up a goats ahole
    Rano is latin mean man who suck homo dick while sticking unit inch dick up muslim goat ahole

    ReplyDelete
  11. Awesome!!

    It might help you!!
    http://www.code-sample.com/2014/04/webgrid-in-mvc-4-razor.html

    ReplyDelete
  12. very good article,keep posting

    ReplyDelete