Create simple WebGrid in MVC (Razor engine)

Controller

public class WebGridExampleController : Controller
{
public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =ย  “INDIA” },
new Country() { CountryId = 2, CountryName= “US” },
new Country() { CountryId = 3, CountryName= “Russia” },
new Country() { CountryId = 4, CountryName= “UK” }
};

return View(obj);
}
}

View

@model RegistrationForm.Models.UserDetailModel
@{
ViewBag.Title = “Index”;
}
<style type=”text/css”>
th
{
font-size: 14px;
font-weight: normal;
color: #039;
padding: 10px 8px;
}
table
{
font-family: arial,sans-serif;
font-size: 11px;
border-width: 1px;
border-color: black;
}
table th
{
background: #D3D3D3;
border-width: 1px;
border-style: solid;
border-color: black;
}
table td
{
background: #AFEEEE;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: black;
}
.foot
{
text-align: center;
}
</style>
<h2>
Country Details</h2>
@{

var grid = new WebGrid(source: Model.CountryDetail, rowsPerPage: 3, canPage: true, canSort: true);

<div id=”grvCountry”>
@grid.GetHtml(
fillEmptyRows: false, mode: WebGridPagerModes.All,
htmlAttributes: “width:100%”, firstText: “<< First”,
previousText: “< Prev”, nextText: “Next >”,ย  lastText: “Lastย  >>”,
columns: new

[]
{ย  grid.Column(“CountryId”, header: “Country ID”, style: “column1”),
grid.Column(“CountryName”, header: “Country Name”, style: “column2”),
ย ย  })
</div>
}

Output :

Webgrid 1

Webgrid 2

Explanation:

ย ย ย ย ย  In first line(var grid…), we are assigning the mode,
rowperpage : how many rows want to display in Webgrid,
canpage : here want to set the default pagination in the webgrid to be true/false
canSortย  : here want to set filter based on the column header (true/false)

Model.CountryDetail : Here being binding the other class inside the UserDetailModel model…