Search code examples
cssasp.net-mvc-3webgridrazor-grid

WebGrid Alignment in MVC3 with RAZOR


I want to set different - different width and alignment in all the columns in WEBGRID in MVC 3. It means that In the above code I have 5 columns now I want to set different alignment and width of all the headers.

Below is my code :

@{WebGrid grid = new WebGrid();
  if (@Model.VendorItemsList != null)
  {
      grid = new WebGrid(source: @Model.VendorItemsList, ajaxUpdateContainerId:         "gridSearch", canSort: true, rowsPerPage: Model.PageSize);
  }
}
<div id="gridSearch" class="tableGrid">
    @{            
        @grid.GetHtml(
            mode: WebGridPagerModes.All,
            columns: grid.Columns(
            grid.Column("VendorItemName", header: @GeneralResource.Vendor + " " + @GeneralResource.Item + " " + @GeneralResource.Name),
            grid.Column("ItemName", header: @GeneralResource.Item),
            grid.Column("ItemCategoryName", header: @GeneralResource.Category),
            grid.Column("VendorName", header: @GeneralResource.Vendor)
            ))
        }
    }
</div>

Solution

  • Since there isn't a built-in way to control the widths, you'll have to use CSS styling. First give classes to the header and body rows:

    @grid.GetHtml(
        headerStyle: "header_row", 
        rowStyle: "item_row"
        // ...
    )
    

    Then style them using the nth-child pseudo-class selectors, eg:

    tr.header_row th:nth-child(1) { width: 100px; }
    tr.header_row th:nth-child(2) { width: 75px; }
    tr.header_row th:nth-child(3) { width: 50px; }
    
    tr.item_row td:nth-child(1) { width: 100px; }
    tr.item_row td:nth-child(2) { width: 75px; }
    tr.item_row td:nth-child(3) { width: 50px; }