Home > DeveloperSection > Blogs > WebGrid in ASP.NET MVC4

WebGrid in ASP.NET MVC4


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 8311  View(s)
Rate this:

WebGrid in ASP.NET MVC4

In this blog I'll introduce WebGrid and show how it can be used in ASP.NET MVC 4, WebGrid is a Predefine tool it's look like tabular format, in this application I’m using the Razor view engine.

Getting Started with WebGrid

To demonstrate a simple example of WebGrid, I’ve creating an ASP.NET MVC action and add values in a list which is student types and pass to the view. My HomeController class has the following action:

public ActionResult Index()

        {

            List<Student> listStudent = new List<Student>();

            listStudent.Add(new Student { StudentID = 1001, StudentName = "Jhon", IsSportsMan = false });

            listStudent.Add(new Student { StudentID = 1002, StudentName = "Spelondar", IsSportsMan = true });

            listStudent.Add(new Student { StudentID = 1003, StudentName = "Alex", IsSportsMan = false });

            listStudent.Add(new Student { StudentID = 1004, StudentName = "Screws", IsSportsMan = true });

            listStudent.Add(new Student { StudentID = 1005, StudentName = "Bekam", IsSportsMan = false });

            listStudent.Add(new Student { StudentID = 1006, StudentName = "Rox", IsSportsMan = true });

            listStudent.Add(new Student { StudentID = 1007, StudentName = "Fezuiz", IsSportsMan = false });

            listStudent.Add(new Student { StudentID = 1008, StudentName = "Raxo", IsSportsMan = true });

            listStudent.Add(new Student { StudentID = 1009, StudentName = "Jeetu", IsSportsMan = false });

            listStudent.Add(new Student { StudentID = 1010, StudentName = "Jay", IsSportsMan = true });

            return View(listStudent);

        }

StudentClass

public class Student

    {

        public int StudentID { get; set; }

        public string StudentName { get; set; }

        public bool IsSportsMan { get; set; }

    }

The List view includes the following Razor code, which renders the grid shown:

@model IEnumerable<WebGridMvc.Models.Student>

@{

    WebGrid studentGrid = new WebGrid(Model);

    Func<bool, MvcHtmlString> func =

    (b) => b ? MvcHtmlString.Create("checked=\"checked\"") : MvcHtmlString.Empty;

}

@studentGrid.GetHtml(columns:  studentGrid.Columns(

studentGrid.Column("StudentID", format: @<text>@item.StudentID</text>),

studentGrid.Column("StudentName", format: @<text>@item.StudentName</text>),

studentGrid.Column("IsSportsMan", format: @<text>

<input name="IsSportsMan" type="checkbox" @func(item.IsSportsMan) /></text>)

))

Output: -

Note: - if I use in WebGrid constructor rowsPerPage: 5 then shows our grid in paging like below: -


Don't want to miss updates? Please click the below button!

Follow MindStick