Using WebGrid to populate data as gridview in ASP.NET MVC RazorView

Chakravarthi
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 160334 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, I would like to discuss using webgrid helper class to populate data in tabuular foramt in asp.net mvc Razor view engine.


 Download source code for Using WebGrid to populate data as gridview in ASP.NET MVC RazorView


To populate data, first we need some data. For that we have to create a simple model, controller and view with some few properties and here I have first created a screen that helps us to insert data into the database.

Model:

Person.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace MVC_myfirst_Mvcapplication.Models
{
    public class Person
    {
        public int ID { get; set; }

        [Required]
        [StringLength(30)]
        public string First { get; set; }

        [Required]
        [StringLength(30)]
        public string Last { get; set; }
        public DateTime Birthdate { get; set; }
    }

    public class PersonContext : DbContext
    {
        public DbSet<Person> People { get; set; }

    }
    
}
Controller :

PersonController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_myfirst_Mvcapplication.Models;

namespace MVC_myfirst_Mvcapplication.Controllers
{
    public class PersonController : Controller
    {
        PersonContext db = new PersonContext();
        //
        // GET: /Person/

        public ActionResult Index()
        {
            var People = db.People.ToList();
            return View(People);
        }

        //
        // GET: /Person/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Person/Create

        [HttpPost]
        public ActionResult Create(Person Person)
        {
            
            db.People.Add(Person);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        
        
    }
}
View:

Person >
Create.cshtml 

@model MVC_myfirst_Mvcapplication.Models.Person

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Person</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.First)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.First)
            @Html.ValidationMessageFor(model => model.First)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Last)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Last)
            @Html.ValidationMessageFor(model => model.Last)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Birthdate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Birthdate)
            @Html.ValidationMessageFor(model => model.Birthdate)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
 Now we need to create some persons as shown bellow 


                                 fig : to create person


                                            fig : after creating some persons

Using WebGrid in ASP.NET MVC



Now we have simple database of persons. Then we need to create a controller and view to show person data as  grid view using webgrid helper class

Controller :

PersonListController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_myfirst_Mvcapplication.Models;

namespace MVC_myfirst_Mvcapplication.Controllers
{ 
    public class PersonListController : Controller
    {
        private PersonContext db = new PersonContext(); // database context for persons

        //
        // GET: /PersonList/

        public ViewResult Index()
        {
            return View(db.People.ToList()); 
        }

       

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

View :

PersonList >

Index.cshtml

@model IEnumerable<MVC_myfirst_Mvcapplication.Models.Person>

@{
    ViewBag.Title = "People List";
}

<h2>People List</h2>

<div id ="DivGrid">
    @{
        var grid = new WebGrid(source: Model);
        @grid.GetHtml(htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
        grid.Column("ID"),
        grid.Column("First"),
	grid.Column("Last"), 
        grid.Column("Birthdate"), 
        grid.Column("", header: "ToEdit", format: @<text>@Html.ActionLink("Edit", "Edit", "Person", new { id = item.ID}, new { target = "_blank" })</text>)));
        }
        
</div>

The simple grid view using webgrid helper class as shown bellow :



if we want to add some features and styles to this webgrid, then we have to use some constructed parameters, GetHtml Parameters for WebGrid 

WebGrid Constructed Parameters used in this view :

Source : Used to render Data into table. This is IEnumerable<dynamic> type, i.e. source: Model
canSort : used to enable or disable sorting data. default is enabled, this is bool type i.e. canSort : true
canPage : used to enable or disable paging data. default is enabled, this is bool type i.e. canPage : true 
rowsPerPage : Used to control no.of rows per page to be rendered. Default is 10, this is Int type i.e. rowsPerPage:3
defaultSort : used to specify the default column to sort. This is string type i.e. defaultSort : "ID"

WebGrid GetHtml Parameters used in this View :

tableStyle : Used to define a table class style for styling. This is string type, i.e. 
tableStyle: "PGrid" 
headerStyle : Used to define a header class style for styling. This is string type, i.e. headerStyle: "Header"
alternatingRowStyle: Used to define  row class for styling even rows. This is string type i.e alternatingRowStyle:"altRow" (for odd rows we have to use rowStyle parameter)



Content >
StyleSheet.css
body 
{
    background-color: #e295fc;
    color: #1A1A1A;
    font-size: .85em;
    font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif;
    margin: 1.5em;
    padding: 0;
}

.PGrid 
{
    margin:2%;
    border-collapse:collapse;
    width:95%;
}
.Header 
{
    font-weight:bold;
    background-color:#60acf6;
    color:#ff6a00;
    text-decoration:none;
}
.PGrid th, .PGrid td
{
    border:1px solid #0094ff;
    padding:5px;
}
.altRow {
    color:brown;
    background-color:#808080;
}

View :

PersonList >

Index.cshtml

@model IEnumerable<MVC_myfirst_Mvcapplication.Models.Person>

@{
    ViewBag.Title = "People List";
}
<link href="../Content/StyleSheet.css" rel="stylesheet" />
<h2>People List</h2>

<div id ="DivGrid">
    @{
        var grid = new WebGrid(source: Model, canPage: true, rowsPerPage:4, defaultSort:"ID");
        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", htmlAttributes: new { id = "DataTable" }, 
columns: grid.Columns(
        grid.Column("ID"),
        grid.Column("First" , "Name"), 
        grid.Column("Birthdate"), 
        grid.Column("", header: "ToEdit", format: @<text>@Html.ActionLink("Edit", "Edit", "Person", new { id = item.ID}, new { target = "_blank" })</text>)));
        }
        
</div>

Finally the customized grid view data using WebGrid as shown bellow: 







Conclusion


Thanks for reading , this is my first article so that i'm not up to the mark in proper way of explanation. If there is any mistakes please let me know by responding to this article. Guiide me to improve my skill set. 

If you find this would be helpful, please leave a comment here. Thanks :-)

Page copy protected against web site content infringement by Copyscape

About the Author

Chakravarthi
Full Name: Annabattula Ashok Chakravarthi
Member Level: Starter
Member Status: Member
Member Since: 7/4/2013 11:49:03 PM
Country: India
Chakravarthi
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Chandradev819 on: 5/21/2014 | Points: 25
You have written in very nice way.

Login to post response

Comment using Facebook(Author doesn't get notification)