Thursday, August 1, 2013

Using WebGrid in MVC 4 Razor | Example Binding WebMatrix Grid in Asp.net 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 Asp.net MVC Razor.

Example :

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

or

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.



Code:

@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> 
<html> 
    <head> 
        <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;} 
        </style> 
    </head> 
    <body> 
        <h1>Employee Details</h1> 
        <div id="grid"> 
            @grid.GetHtml( 
                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("employeeid"), 
                    grid.Column("Salary", format:@<text>$@item.contact</text>) 
                ) 
            ) 
        </div> 
    </body> 
</html>

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

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


Output:



No comments:

Post a Comment