Hi

Creating gridview in Mvc Step By Step

Simple gridview Steps:
Step 1 : Open Visual Studio 2010.
  • Go to file -> New->Projects.
  • Create an ASP.NET MVC 3 Web Application.
  • Name of "WebGrid".
start.gif
strtttt.gif
interstart.gif
Step 2 : Add a class in the model folder.
  • Right click on the Models folder ->add new items->add class.
  • Name of Class is "Employee".
  • In a class define the properties.
addclass.gif
ccccccccccccccccccccc.gif
Step 3 : Define the properties in Employee class.

Code
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Webgrid.Models
{
    public class Employee    {
        public string FirstName { getset; }
        public string LastName { getset; }
        public double Salary { getset; }
        public static List<Employee> GetList()
        {
            List<Employee> Employees = new List<Employee>{
          new Employee   { FirstName="Rahul", LastName="Kumar", Salary=45000},
          new Employee   { FirstName="Jose", LastName="Mathews", Salary=25000},
          new Employee   { FirstName="Ajith", LastName="Kumar", Salary=25000},
          new Employee   { FirstName="Scott", LastName="Allen", Salary=35000},
            new Employee   { FirstName="Abhishek", LastName="Nair", Salary=125000}
            };
            return Employees;
        }
    }
}
Step 4 : Add a controller.
  • Right click on the Controllers folder ->add->Controllers.
  • Name of Controllers is "Home".
  • In a controller, define the request.
controller.gif
controname.gif
Step 5 : Write the code on controller.
Code
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Webgrid.Models;namespace Webgrid.Controllers
{
    public class HomeController : Controller    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult show()
        {
            var empoyees = Employee.GetList();
            return View(empoyees);
        }
    }
}
Step 6 : Add the  view.
  • Right click of index methods->add view
  • The name of view is "index".
view.gif
viewsssss.gif
Step 7 : Write the code on view.
Code
@model Webgrid.Models.Employee@{    Layout = null;}
@{
        
   var grid = new WebGrid(source: Model,
                defaultSort: "FirstName",
                rowsPerPage: 3);
}<h2>Employee List</h2><div id="grid">    @grid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt",
        columns: grid.Columns(
            grid.Column("FirstName"),
            grid.Column("LastName"),
            grid.Column("Salary",format:@<text>$@item.Salary</text>)
        )
    )
</div>
Step 8 : Press Crtl+F5 to run application.
Output:
output.gif
Previous
Next Post »