pavanarya

Let us share the knowledge

Displaying data in a grid using WebGrid in cshtml

with 12 comments

Hi,
In this post i want to write about WebGrid class which is used to render html table content.

I am having a class that contains few properties which is my actual model class and i want to render a list of my model class objects in the form of a grid.
Previously in web forms we used to have GridView but in MVC3 we have something like WebGrid().

Now let us create our model class with few properties.

MyModel.cs

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

namespace MvcApplication2.Models
{
    public class MyModel
    {
       
        public string firstname{set;get;}
        public string lastname{set;get;}
        public string AddressCity { set; get; }
        public string FullName { set; get; }
        public string nicknameFirstNmae { set; get; }

        public string profession { set; get; }
        public string designation { set; get; }
        public string experience { set; get; }

    }
}

Now let us create a controller by name FirstController and it is having a method called Test() that renders a view called myFirstView.cshtml. This view is going to render the grid.

FirstController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Web.Mail;

namespace MvcApplication2.Controllers
{
    public class FirstController : Controller
    {
       
        public ActionResult Test()
        {
             Models.MyModel mod = new Models.MyModel();
            Models.MyModel mod1 = new Models.MyModel();
            List<Models.MyModel> lst = new List<Models.MyModel>();
            mod.AddressCity = "Vizag";
            mod.firstname = "Pavan";
            mod.lastname = "Kumar";
            mod.nicknameFirstNmae = "PavanArya";
            mod.FullName = "Pavan Kumar Aryasomayajulu";
            mod.experience = "2yrs";
            mod.designation="Associate s/w engineer";
            mod.profession="Information Technology";

            mod1.AddressCity = "Vizag";
            mod1.firstname = "Kiran";
            mod1.lastname = "Kumar";
            mod1.nicknameFirstNmae = "KiranMantri";
            mod1.FullName = "Kiran Kumar Mantri";
            mod1.experience = "3yrs";
            mod1.designation = "s/w engineer";
            mod1.profession = "Information Technology";
            lst.Add(mod);
            lst.Add(mod1);

            return View("myFirstView", lst);
        }

    }
    
}

In this controller we are creating an object of MyModel class and assigning them values. And at last we are adding these objects to a List.

Now coming to our View. In order to create a grid inside a view. First create an object of WebGrid(our_model_obj).
Note: Our Model object should be of type IEnumerable.

Now there is a method called GetHtml() which accepts few optional parameters. This method returns the html table content.

myFirstView.cshtml

@{
        //Layout = null;
}
@model IEnumerable<MvcApplication2.Models.MyModel>
    <div>
@{
    var grid = new WebGrid(@Model); 
}
@grid.GetHtml()
    </div>

This is the basic grid that is displayed.

Customizing Grid and applying styles

Now let us create a grid that is not going to display all the fields of our MyModel class and also we are creating few styles for this Grid.

Now in this grid i just want to display firstname and lastname fields only.

So in order to do that initially we are supposed to create a list that contains all the column names that we want to display and then send it to WebGrid constructor.

Note: It contains many more parameters that can define number of rows per page,columns to display,default sort value and many more.
But for now i just want to discuss about columns to be displayed.

    List<string> ls=new List<string>();
    ls.Add("firstname");
    ls.Add("lastname");
    IEnumerable<string> columnnames = ls.AsEnumerable<string>();
    var grid = new WebGrid(@Model,columnNames:columnnames);

Note: in the list of columnnames we specify any name that is not present in the MyModel class then it is going to throw an exception
Column “xyz” does not exist.

Specifying styles to the grid.

The method GetHtml() accepts options parameters where we can specify which style should be applied to the columns, header,footer etc.

@grid.GetHtml(
tableStyle: "grid",
         headerStyle: "grid-header",
      alternatingRowStyle: "grid-alternating-row",
       selectedRowStyle: "grid-selected-row",
             rowStyle: "grid-row-style"
             )

myFirstView.cshtml

@{
        //Layout = null;
}
@model IEnumerable<MvcApplication2.Models.MyModel>

    <div>
@{
    List<string> ls=new List<string>();
    ls.Add("firstname");
    ls.Add("lastname");
    IEnumerable<string> columnnames = ls.AsEnumerable<string>();
    var grid = new WebGrid(@Model,columnNames:columnnames);
    
}
@grid.GetHtml(
tableStyle: "grid",
         headerStyle: "grid-header",
      alternatingRowStyle: "grid-alternating-row",
       selectedRowStyle: "grid-selected-row",
             rowStyle: "grid-row-style"
             )
    </div>


Add below css items to existing Style.css file

site.css

.grid
   {
       width: 50%;
       border: 0px;
       border-collapse: collapse;
   }
    
   .grid a
   {
       color: #000;
   }
    
    .grid-row-style td
    {
        text-align:center
    }
    .grid-header th
    {
        padding-right:20px;
        padding-left:20px;
    }
    .grid-alternating-row td
    {
        text-align:center
    }
   .grid-header
   {
       padding: 6px 5px;
       text-align: center;
       background-color: #e8eef4;
       border-bottom: 2px solid #3966A2;
       height: 40px;
    
       border-top: 2px solid #D6E8FF;
       border-left: 2px solid #D6E8FF;
       border-right: 2px solid #D6E8FF;
   }
    
   .grid-footer
   {
       padding: 6px 5px;
       text-align: center;
       background-color: #e8eef4;
       border-top: 2px solid #3966A2;
       height: 30px;
    
       border-bottom: 2px solid #D6E8FF;
      border-left: 2px solid #D6E8FF;
       border-right: 2px solid #D6E8FF;
   }
    
   .grid-alternating-row
   {
      height: 30px;
       background-color: #f2f2f2;
       border-bottom: 1px solid #d2d2d2;
    
       border-left: 2px solid #D6E8FF;
       border-right: 2px solid #D6E8FF;
  }
    .grid-row-style
   {
      height: 30px;
      border-bottom: 1px solid #d2d2d2;
    
      border-left: 2px solid #D6E8FF;
       border-right: 2px solid #D6E8FF;
   }
    
   .grid-selected-row
   {
       font-weight: bold;
   }

Thanks,
Pavan

About these ads

Written by pavanarya

July 4, 2012 at 10:02 pm

Posted in MVC

12 Responses

Subscribe to comments with RSS.

  1. Hi Pavan,
    @{
    var grid = new WebGrid(@Model);
    }

    Thanks for the lovely post I am getting below error while trying to running above portion .. could you please help me out how to resolve this
    CS1502: The best overloaded method match for ‘System.Web.Helpers.WebGrid.WebGrid(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable, string, int, bool, bool, string, string, string, string, string, string, string)’ has some invalid arguments

    Dhiren

    July 5, 2012 at 10:53 am

    • Dhiren are you trying to exactly run my code given in the example. If not can you send me the code piece that you were using.
      My Mail :pavan.aryasomayajulu@gmail.com

      Thanks,
      Pavan

      pavanarya

      July 5, 2012 at 11:19 am

      • Hi I am using VS 2010 SP1

        Model Page :
        public class Customer
        {
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public double Salary { set; get; }
        }

        Controller:
        public class CustomerController : Controller
        {
        //
        // GET: /Customer/
        List custLst = new List()
        {
        new Customer {FirstName=”Vinay”,LastName=”Gowda”,Salary=20.20},
        new Customer {FirstName=”Sourav”,LastName=”Mukherjee”,Salary=30.00},
        new Customer {FirstName=”Jyoti”,LastName=”Mishra”,Salary=35.00}
        };
        public ActionResult Index()
        {

        return View(custLst);
        }
        //This is my controller where I am trying to generate grid
        public ActionResult RazorGrid()
        {
        ViewBag.Result = custLst;
        return View(“RazorGrid”, custLst);
        }

        }

        View Page :

        @model RazorApplication.Models.Customer
        @using System.Dynamic
        @{
        @* var testgrid = new WebGrid(@model)*@
        var testgrid = new WebGrid(source:Model,defaultSort:”FirstName”,rowsPerPage:3);
        }
        @{
        Layout = null;
        }

        RazorGrid

        @using (Html.BeginForm())
        {

        @testgrid.GetHtml()

        }

        Dhiren

        July 5, 2012 at 2:08 pm

      • Hi Dhiren,
        In the view part when we are using
        var testgrid = new WebGrid(source:Model,defaultSort:”FirstName”,rowsPerPage:3);

        Model object should be of type iEnumerable.

        So you can use something like

        @model IEnumerable<MvcApplication1.Models.Customer>
        instead of 
        @model MvcApplication1.Models.Customer
        

        Or else
        At the time of sending the model object to view using return View()

        we can make the customer object list as enumerable as follows
        return View(“RazorGrid”, custLst.AsEnumerable());

        Thanks,
        pavan

        pavanarya

        July 5, 2012 at 2:36 pm

  2. Hi Pavan ,

    Thanks for your reply ..

    I have modified my controller code to
    return View(“RazorGrid”, custLst.AsEnumerable());

    and view is same but still I am getting the same error

    It will be great if you will give me the code how the controller and view should be .

    I am new to razor view and today I have started …

    Dhiren

    July 5, 2012 at 3:39 pm

    • Hi,
      Undo your controller changes back to
      return View(“RazorGrid”, custLst);

      and change the view to

      @model IEnumerable<MvcApplication1.Models.Customer>
      @using System.Dynamic
      @{
      @* var testgrid = new WebGrid(@model)*@
      var testgrid = new WebGrid(source:Model,defaultSort:”FirstName”,rowsPerPage:3);
      }
      @{
      Layout = null;
      }

      RazorGrid

      @using (Html.BeginForm())
      {

      @testgrid.GetHtml()

      }

      This should work fine.
      Thanks,
      pavan

      pavanarya

      July 5, 2012 at 4:50 pm

      • Pavan : Now I am getting the below error when I have used the above code ,…

        Compiler Error Message: CS0305: Using the generic type ‘System.Collections.Generic.IEnumerable’ requires 1 type arguments

        public class _Page_Views_customer_RazorGrid_cshtml : System.Web.Mvc.WebViewPage {

        Dhiren

        July 5, 2012 at 5:17 pm

      • Hi Dhiren,Just now mailed you the working version of the webGrdid post to your mail dhiren_kaunar@rediffmail.com

        Please validate it and let me know.
        Thanks,
        Pavan

        pavanarya

        July 5, 2012 at 8:48 pm

  3. Hi Pavan,

    Thanks its working fine .. Thanks a lot.. Could you please suggest some good link where we can get more knowledge on MVC3 and razor..

    Dhiren

    July 5, 2012 at 9:51 pm

  4. [...] used to render a Model class data to a grid i came across an interesting fact. Please check my post Displaying data in a grid using WebGrid in cshtml before reading this if you are new to WebGrid class in [...]

    • Hi Pavan. Thank you for this post but I am facing a problem. I tried this but nothing is getting displayed in my case. I have also checked and i am sure that the view is getting returned with the collection of objects.
      Please tell me where i am going wroung. Thanks in advance.

      vidushi

      August 9, 2012 at 12:19 pm

      • Hi Vidushi,
        Can you please mail me the code you are using. So that i can verify.
        My emainId:pavan.aryasomayajulu@gmail.com
        Thanks,
        Pavan

        pavanarya

        August 9, 2012 at 12:34 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: