Retrieving Database Values with Telerik Grid in Razor MVC 3


In this article, we will see how to retrieve the database values using telerik grid and show the output into new enhanced UI.  So, here for this requirement we need to use Telerik Extensions for MVC.

I am just creating a Student Class in Model folder with Some Properties in it where the complete code of Student.cs looks like this:

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

namespace TelerikMvcApplication3.Models
{
    public class Student
    {
        [Key]
        public int StudentId { get; set; }

        [Required(ErrorMessage = "Please Enter FirstName")]
        [StringLength(10, ErrorMessage = "FirstName morethan 10 charcs")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Please Enter LastName")]
        [StringLength(10, ErrorMessage = "LastName morethan 10 charcs")]
        public string LastName { get; set; }

        [Range(5, 50, ErrorMessage = "Age Should Be Between 5 and 50")]
        public int Age { get; set; }

        [Required(ErrorMessage = "Please Enter Location")]
        [StringLength(10, ErrorMessage = "Location morethan 10 charcs")]
        public string Location { get; set; }


    }
}

We used Dbset<> in StudentStateEntities.cs where it's kept in Model Folder to wrap up the student class code. Where it looks like this:

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

namespace TelerikMvcApplication3.Models
{
    public class StudentStateEntities:DbContext
    {
        public DbSet<Student> Students { get; set; }
    }

The Initializer class is also created to handle database or requirement changes for the application to maintain and handle situation. So the Complete code of StudentStateIntializer.cs looks like this. It's kept in Model's Folder:

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

namespace TelerikMvcApplication3.Models
{
    public class StudentStateIntializer:DropCreateDatabaseIfModelChanges<StudentStateEntities>
    {
        protected override void Seed(StudentStateEntities context)
        {
            var stu = new List<Student>
            {
                new Student
                {
                   StudentId=1,
                    FirstName="Vijay",
                    LastName="Prativadi",
                    Location="Banglore",
                    Age=25
                },
                 new Student
                {
                    StudentId=2,
                    FirstName="Uday",
                    LastName="Prativadi",
                    Location="Mumbai",
                    Age=28
                }
            };
            stu.ForEach(p=>context.Students.Add(p));
        }
    }
}


We will now go into global.asax and add a basic one line code to handle database changes for our intializer class:

Database.SetInitializer<StudentStateEntities>(new StudentStateIntializer());

So the Complete Code of Global.asax looks like this:

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

namespace TelerikMvcApplication3
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            Database.SetInitializer<StudentStateEntities>(new StudentStateIntializer());
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}


We are now adding Home Controller with Controller with read/write actions and views using Entity Framework:

So the Code looks like this:

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

namespace TelerikMvcApplication3.Controllers
{
    public class HomeController : Controller
    {
        private StudentStateEntities db = new StudentStateEntities();

        //
        // GET: /Home/

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

        //
        // GET: /Home/Details/5

        public ViewResult Details(int id)
        {
            Student student = db.Students.Find(id);
            return View(student);
        }

        //
        // GET: /Home/Create

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

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index"); 
            }

            return View(student);
        }
       
        //
        // GET: /Home/Edit/5
 
        public ActionResult Edit(int id)
        {
            Student student = db.Students.Find(id);
            return View(student);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        //
        // GET: /Home/Delete/5
 
        public ActionResult Delete(int id)
        {
            Student student = db.Students.Find(id);
            return View(student);
        }

        //
        // POST: /Home/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {           
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

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


So for the created view of Index.cshtml we will now make basic changes to the predefined code to add telerik extensions. So the Complete code of Index.cshtml looks like this.

@model IEnumerable<TelerikMvcApplication3.Models.Student>
} <h2>Index</h2> <p>
@using Telerik.Web.Mvc.UI @{ ViewBag.Title = "Index"
; @Html.ActionLink("Create New", "Create") </p> <div>
.Columns(columns =>
@(Html.Telerik().Grid(Model) .Name("Grid")
{ columns.Bound(o => o.FirstName).Width(100);
columns.Bound(o => o.Age).Width(100);
columns.Bound(o => o.LastName).Width(100);
columns.Bound(o => o.Location).Width(100); }) .Scrollable() .Pageable()
.Footer(true)
.Sortable() .Filterable() .Groupable() .NoRecordsTemplate("No Records Found")
)
 
</div>

So finally we are done now. So, let's rebuild and run the application where the output looks like this:

Grid1.jpg

Filtering the Name starts with specific value the output looks like this:

  Grid2.jpg

Grid3.jpg.png

When there are no records found it will display a friendly message to user where the output looks like this
 

Grid4.jpg.png
 

 I hope this article is useful to you. I look forward for your comments and feedback .

Up Next
    Ebook Download
    View all
    Learn
    View all
    MVC Corporation is consulting and IT services based company.