Follow by Email

Thursday, August 1, 2013

Using WebGrid in MVC 4 Razor | Example Binding WebMatrix Grid in MVC 4 Razor | Sorting paging Grid in MVC Razor

Hi in this post i will show how to use a webgrid and also how to do paging sorting in it using MVC Razor.

Example :

Some times @using namespace is not accessible so we need to add reference for WebMatrix.Data and WebMatrix.WebData


you can directly copy the dll from "C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies" and copy into the bin folder of the application.


@using WebMatrix.Data;
    var db = Database.Open("MyNewConnection"); 
    var selectQueryString = "SELECT * FROM Employee"; 
    var data = db.Query(selectQueryString); 
    var grid = new WebGrid(source: data,
                           defaultSort: "employeename",  
                           rowsPerPage: 10); 
    grid.SortDirection = SortDirection.Ascending;
<!DOCTYPE html> 
        <title>Displaying Data Using the WebGrid</title> 
        <style type="text/css"> 
            .grid { margin: 4px; border-collapse: collapse; width: 600px; } 
            .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; } 
            .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; } 
            .alt { background-color: #E8E8E8; color: #000; } 
            .empname { width: 200px; font-weight:bold;} 
        <h1>Employee Details</h1> 
        <div id="grid"> 
                tableStyle: "grid", 
                headerStyle: "head", 
                alternatingRowStyle: "alt", 
                columns: grid.Columns( 
                    grid.Column("employeename", "Employee Name", style: "empname"), 
                    grid.Column("Location", format:@<i>@item.location</i>), 
                    grid.Column("Salary", format:@<text>$</text>) 

In the webconfig file of the application add new connection string:

      <add name="MyNewConnection" connectionString="Data Source=.;Initial Catalog=SampleDB;Integrated Security=True"
           providerName="System.Data.SqlClient" />