ARTICLE

Telerik Grid View in ASP.NET MVC2: Part 1

Posted by Kumar Saurabh Articles | ASP.NET MVC with C# October 12, 2011
In this article I will be demonstrating how to populate a Telerik Grid View in ASP.NET MVC2 using Entity Framework 4.
Reader Level:
Download Files:
 

In this article I will be demonstrating how to populate a Telerik Grid View in ASP.NET MVC2 using Entity Framework 4.

Please go through my artcle - Working with Telerik Controls in ASP.NET - This article will explain all of the prerequisites for working with Telerik controls in APS.NET MVC Projects.

For demonstration here, I will be using here Visual Studio 2010(MVC2.0)

1. Create a new ASP.NET MVC2 Web application - name it as MVCTelerikGridViewDemo

TlrkASPNET1.gif

2. For this sample application - Let's not create the unit test project.- So select the radio button - No, Do not create a unit Test Project.

3. Now we have the readymade/default ASP.Net MVC2 Project template with few files already existing in each of the folders Model , View and Controller.

4. For this Demo - We will be placing the Telerik Grid View in existing default View ( Views ->Home->Index.aspx)
This View is called from HomeController.cs(Controller -> HomeController.cs)

5. Create ViewModel

  • ViewModel can be thought as a Model - which is responsible to supply information to a View.
  • ViewModels helps us to create Strongly Typed Views.
  • Right Click solution explorer -> MVCTelerikGridViewDemo -> Add -> New Folder(ViewModel) = This folder can be used for placing all the ViewModel classes of the entire project.
  • Right Click ViewModels -> Add Class -> IndexTelerikGridViewModel.cs

    TlrkASPNET2.gif
     
  • Open IndexTelerikGridViewModel.cs -Include automatic properties representing each of the columns of the GridView.

Code - IndexTelerikGridViewModel.cs

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

namespace MVCTelerikGridViewDemo.ViewModel
{
    public class IndexTelerikGridViewModel
    {
        public int iArticleID { get; set; }
        [Required]
        public String sTitle { get; set; }
        [Required]
        public string sSection { get; set; }
        [Required]
        public int iViews { get; set; }
        [Required]
        public int iDownloads { get; set; }
        [Required]
        public string sStatus { get; set; }

    }
}

6. Database Part

  • We will create a sample SQL Server database - create a table and insert some sample data which would be reflected in our Telerik GridView.

  • For this sample app - Let us create table by

    1. Right Click the App_Data folder -> Add -> New Item -> Select SQL Server database and give it some name- TestDatabase.mdf - Click Add.
    2. Double Click TestDatabase.mdf to open the Server Explorer.
    3. Right Click Table - Add New Table -
    - ArticleID- Primary Key(set to autoincrement by 1)

    TlrkASPNET3.gif

    4. Save- (CTRL+S) -> Give Table Name -> MyArticles
    5. Insert Sample Data - Right-click the tblState table and select option Show Table Data- and you can enter sample data.

7. Setting up the Models

  1. Adding Entity Framework classes
     

    • Entity Framework is an ORM(object relational mapper) that ships as part of .Net 4
    • From the Solution explorer -> Go to Models folder -> Right Click Models -> Add New Item -> Select ADO.Net Entity Data Model -> Name it -> TestDataBaseModel.edmx -> Click Add -
    • Below Screenshots depicts the stepwise creation of Entity Framework Class.


      TlrkASPNET4.gif

      TlrkASPNET5.gif

      TlrkASPNET6.gif

      TlrkASPNET7.gif
       
    • With the Click on Finish - Our Entity Data Model is created.

      TlrkASPNET8.gif
       
  2. Creating a Repository Class
     

    • This approach using a Repository class helps encapsulate data querying and persistence logic.
    • In the Repository Class - We can specify all the Querying methods required in our application
    • Right Click Models-Add Class - DataRepository.cs

      TlrkASPNET9.gif
       
    • Open DataRepository.cs
    • Add the following using Statement

    • using System.Web.Mvc;
      using MVCTelerikGridViewDemo.ViewModel;
       
    • Create the object of TestDatabaseEntities
    • Include a function which would fetch the records to be displayed in Telerik Grid View

      Code-DataRepository.cs

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.Mvc;
      using MVCTelerikGridViewDemo.ViewModel;

      namespace MVCTelerikGridViewDemo.Models
      {
          public class DataRepository
          {
              //Create an instance of TestDatabaseEntities
              public TestDatabaseEntities entities =new TestDatabaseEntities(); 
              //Fetching Records from database to be displayed in Telerik Grid
              public IEnumerable<IndexTelerikGridViewModel> MyArticles_DisplayRecords()
              {
                  try
                  {
                      var records =from MyArticle in entities.MyArticles
                                    select new IndexTelerikGridViewModel
                                    {
                                        iArticleID=MyArticle.ArticleID,
                                        sTitle=MyArticle.Title,
                                        sSection=MyArticle.Section,
                                        iViews=MyArticle.Views,
                                        iDownloads=MyArticle.Downloads,
                                        sStatus=MyArticle.Status
                                    };
                      return records;
                  }
                  catch (Exception ex)
                  {
                      return null;
                  }
              }

          }
      }

8. Now you need to perform all the steps which I have mentioned as prerequisites before including a Telerik Control in your Views - Working with Telerik Controls in ASP.NET 

9. Views

Open Index.aspx (default View already existing in Views->Home folder)

• We can strongly type this View to our ViewModel class we created by updating the Page directive as below-

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MVCTelerikGridViewDemo.ViewModel.IndexTelerikGridViewModel>>" %>

  • Include Telerik Grid View in Index.aspx

<%=
 
        Html.Telerik().Grid(Model)
                .Name("tgvArticle")
                    .DataKeys(keys=>keys.Add(c=>c.iArticleID))
                        .Columns(columns=>
                            {
                              
                                columns.Bound(p=>p.sTitle).Title("Title");
                                columns.Bound(p=>p.sSection).Title("Section");
                                columns.Bound(p=>p.iViews).Title("Views");
                                columns.Bound(p=>p.iDownloads).Title("Downloads");
                                columns.Bound(p=>p.sStatus).Title("Status");
                            }).Pageable()
                                .Sortable()
                                    .Filterable()

        %>

10. Controller

  • Our View Index.aspx is called from HomeController.cs (Controller -> HomeController.cs)

  • Open HomeController.cs

  • Add the following using statement

    using MVCTelerikGridViewDemo.Models;
    using MVCTelerikGridViewDemo.ViewModel;

     

  • Create an instance of Repository Class which we created in Model.

    DataRepository objRepository =new DataRepository();
     

  • Update the ActionResult Index to pass the fetched records to be displayed in the View - Index.aspx

    public ActionResult Index()
            {
                ViewData["Message"] ="Telerik Grid View Demo!!!";
                return View(objRepository.MyArticles_DisplayRecords());
            }

     

  • Code HomeController.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVCTelerikGridViewDemo.Models;
    using MVCTelerikGridViewDemo.ViewModel;

    namespace MVCTelerikGridViewDemo.Controllers
    {
        [HandleError]
        public class HomeController :Controller
        {
            DataRepository objRepository = new DataRepository();

            public ActionResult Index()
            {
                ViewData["Message"] ="Telerik Grid View Demo!!!";
                return View(objRepository.MyArticles_DisplayRecords());
            }
        }
    }


11. Output - Run the application

Telerik Grid View would be displayed on the page as -

TlrkASPNET10.gif

Since we have mentioned out Telerik Grid View as Pageable,Sotable and Filterable in code (refer Telerik Grid View Code added in the View)- So all these functionality come with this Grid.

Example - Records can be filtered based on column values

TlrkASPNET11.gif

I will come soon with Part 2 of Telerik Grid View - with the Insert,Update and Delete Operations

Happy Learning!!

 

Login to add your contents and source code to this article
post comment
     

thanx Sourabh finally did it thanx a lot ..

Posted by nilesh monde Mar 08, 2013

how to bind simple gridview in mvc 2 not telerik grid . i read somewhere mvc 2 doesn't support gridview. thanx

Posted by nilesh monde Mar 04, 2013

@Nilesh - not sure if its because of Entity Framework installations. I googled it and came across this issue - Please have a look - http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/600014a4-c02e-465e-bc15-329a5d848899http://forums.asp.net/t/1499854.aspx

Posted by Kumar Saurabh Mar 03, 2013

yes i attempted step 7 but in my vs 2010 ultimate verrsion that icon not shown? to display tat icon in list what can i do?

Posted by nilesh monde Mar 03, 2013

@Nilesh - As mentioned in Point no - 7 - Please follow this step- Add New Item -> Select ADO.Net Entity Data Model .This demo is in VS2010 Ultimate. Please let me know if you still face the issue.

Posted by Kumar Saurabh Mar 03, 2013
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter