WebGrid is used to display the data with paging and sorting
Introduction
This article shows how to use hyperlink in WebGrid using Web API 2..
Lets start creating a simple WebAPI
- Step 1 :Create a New Project Open visual studio 2013 -> click on File -> New Project -> Create new ASP.NET WebApplication -> Name it as SampleWebGrid
Select Web API Template and click on ok
- Step 2 :Now Lets add a Model Right click on Models Folder---->Add class StudentDetail
- Step 3 :Add the below properties to the Model class
using System.Collections.Generic;
namespace SampleWebGrid.Models
{
public class StudentDetail
{
public List<Student> UserCollection { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Student_Name { get; set; }
public int Roll_No { get; set; }
public string Student_Address { get; set; }
}
}
- Step 4 :Now lets modify the HomeController class which is under Controllers folder
using SampleWebGrid.Models;
using System.Collections.Generic;
using System.Web.Mvc;
namespace SampleWebGrid.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
StudentDetail obj = new StudentDetail();
List<Student> studtl = new List<Student>();
studtl.Add(new Student { Id = 1, Student_Name = "Robert", Roll_No = 977, Student_Address = "Bangalore" });
studtl.Add(new Student { Id = 2, Student_Name = "sagar", Roll_No = 889, Student_Address = "Hyderabad" });
studtl.Add(new Student { Id = 3, Student_Name = "swami", Roll_No = 988, Student_Address = "Kolkata" });
studtl.Add(new Student { Id = 4, Student_Name = "babish", Roll_No = 142, Student_Address = "Jaipur" });
studtl.Add(new Student { Id = 5, Student_Name = "sameer", Roll_No = 566, Student_Address = "Pune" });
obj.UserCollection = studtl;
return View(obj);
}
}
}
- Step 5 :Now lets modify the HTML view which is under views folder
@model SampleWebGrid.Models.StudentDetail
@{
ViewBag.Title = "Sample WebGrid";
}
<style type="text/css">
table {
font-family: 'Times New Roman' font-size: 11px;
color: #666666;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #0026ff;
background-color: #ffffff;
}
</style>
@using (Html.BeginForm("Index", "Home"))
{
var grid = new WebGrid(Model.UserCollection, columnNames: new[] { "Student_Name", "Roll_No" });
@grid.GetHtml(columns: grid.Columns(
grid.Column("Student_Name", format: @<text>@Html.ActionLink((string)item.Student_Name, "ActionName", "Controllername", new { id = item.id }, null)</text>),
grid.Column("Roll_No"),
grid.Column("Student_Address")
))
}
Debug the Application and we can see the following window