Published: 08 Nov 2010
By: Xianzhong Zhu
Download Sample Code

In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.

Contents [hide]

The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • Introduction

    In essence, there is more than that. ASP.NET MVC Beta has also created a new kind of ASP.NET Web Pages technology which includes a set of helper methods that are useful for adding commonly used functionality to views and controllers. ASP.NET MVC 3 supports using these helper methods within controllers and views (where appropriate). These methods are contained in the System.Web.Helpers assembly. With these helpers, ASP.NET MVC 3 tends to close that gap in the helpers area compared with other popular MVC frameworks.

    This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.

    NOTE

    The development environments we'll utilize in this series are:

    1. Windows XP Professional (SP3);

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. ASP.NET MVC 3 Beta (http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0abac7a3-b302-4644-bd43-febf300b2c51);

    5. SQL Server 2005/2008;

    6. Northwind and pubs Sample Databases for SQL Server 2000 (URL: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en.You can easily use in the SQL Server 2005/2008).

    The WebGrid Helper

    In this section, we are more concerned about the WebGrid helper. Concretely, WebGrid provides paging and sorting functionality, as well as other goodies. This section will introduce how to use it in the ASPX view engine environment.

    Create a sample project sketch

    Suppose you've installed ASP.NET MVC 3 Beta. Now, start up your Visual Studio 2010 IDE to create an ASP.NET MVC 3 web application, naming it Mvc3WebGridTest_AspxVersion.

    Add the ADO.NET Entity Data Model item template

    Now, you will learn to how to use the Entity Data Model Wizard to generate an .edmx file, which contains a conceptual model, a storage model, and mapping information.

    1. Right click Models, and then select New |New Item...

    2. In then "Add New Item" dialog, from the Installed Templetes choose Data, and then from the right select ADO.NET Entity Data Model.

    3. Type NorthwndModel.edmx for the model name and click Add. Then the Entity Data Model Wizard is displayed.

    4. Select "Generate from database" in the "Choose Model Contents" dialog box. Then click Next.

    5. If your Data Source is not ready, then click the "New Connection" button to select your data source. In my machine, I just need to select the target data source – zxzcom.Northwind.dbo from the "Choose Your Data Connections" dialog box.

    6. Ensure that "Save entity connection settings in App.Config as:" is checked and the value is set to NORTHWNDEntities. Then click "Next". Afterwards, the "Choose Your Database Objects" dialog box is displayed.

    7. Select the Products table and ensure that the value of Model namespace is NorthwindModel. Now, click the "Finish" button, and then the wizard will perform all the rest actions for you.

    Till now, you have successfully generated the conceptual, storage, and mapping content for the NorthwindModel model in the Mvc3WebGridTest_AspxVersion project. Next, you will use action to create queries against the CLR objects that represent our interested entities and possible associations in the model.

    Create an action in the Home controller

    Now, let's create an action in the Home controller (this is for simplicity, you can create or select other controllers on the fly). But first of all, we should add the necessary namespace reference like the following:

    Then, we set up a simple action named ListProducts, as shown in Listing 1.

    Here, we first create an instance of the class NorthwindEntities which generally encapsulates the typical CRUD operations around the entity object Products and other related stuff. Then, we return a ViewResult, with the default view name parameter being the same as that of the action and the model parameter as a list of all product records.

    Create the view

    Now right click the preceding action ListProducts and select "Add View..." dialog box. Then in the "Add View" dialog box, set the name of the view to ListProducts. Note in the View engine related listbox control, the default is ASPX (C#). In this case, just keep all the other options as default, shown in Figure 1.

    Figure 1: Create a view ListProducts using the default ASPX view engine

    Create a view ListProducts using the default ASPX view engine

    After clicking the "Add" button, you will notice the system automatically add a view named ListProducts.aspx under the subfolder Views\Home and opens it. In our case, we modified the view like the following.

    The above code defined a grid in support of both pagination and sorting.

    Moreover, there are still some points worth noticing. First, we've not utilized a strongly-typed class, but called the following:

    Second, note the first parameter source of the helper WebGrid is of type Model. Here, the mysterious Model property, together with the above Inherits invocation, indicates to the MVC engine that the target model comes from NorthwindModel. In the later Chart helper related section you'll see another interesting topic relevant to the Model property.

    Now, press Ctrl+F5 to start up the project and then in the address bar fill in the following url (the port number may differ in your machine) and press ENTER:

    http://localhost:1700/home/listproducts

    You will see something like Figure 2.

    Figure 2: The WebGrid helper in action

    The WebGrid helper in action

    More about the WebGrid helper

    Let's look at the constructor of the WebGrid helper:

    Listing 1: The WebGrid helper declaration

    On the whole, the most commonly-used parameters in this helper are:

    1. source: represents the data source.

    2. columnNames: represents the displayed columns related names.

    3. defaultSort: specifies the default sort means.

    4. rowsPerPage: specifies the row number of data to be shown per page.

    5. canPage: specifies whether to sort the records or not.

    Till now, we've only scratched the surface of the strong WebGrid helper. So, all the rest deeper exploit of this great tool rests upon your readers. In the next section, we are going to introduce another helper – Chart.

    The Chart Helper

    As is well known, using the Chart web control in an ASP.NET WebForms application is easy to accomplish. Also, it's not difficult to achieve this in the ASP.NET MVC environment. One typical way is to use the ASP.NET Server control Chart defined in the System.Web.UI.DataVisualization.Charting namespace typically defined in the assembly C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.DataVisualization.dll. Of course, you can simply drag a Chart control onto the MVC .aspx view page. But it's not recommended to do so. A pretty decent approach to use the Chart control is found by Scott Mitchell in his article "Using Microsoft's Chart Controls In An ASP.NET Application: Using the Chart Controls with ASP.NET MVC" (see url http://www.4guysfromrolla.com/articles/092210-1.aspx). Another article by Michael Ceranski brought a similar way like Scott Mitchell's.

    The Chart helper

    To further simplify the above operations with the Chart control in an ASP.NET MVC Application, Microsoft introduced a new Chart helper bearing the similar features as the <asp:Chart> control in ASP.NET 4 – except now using view helper methods. In this section, we are just going to delve into it.

    Like the ASP.NET Chart control, the Chart helper can render an image that displays data in a variety of chart types. It supports many options for formatting and labeling. The Chart helper can render more than 30 types of charts, including all the types of charts that you might be familiar with from Microsoft Excel or other tools - area charts, bar charts, column charts, line charts, and pie charts, along with more specialized charts like stock charts. Moreover, the Chart helper can take data source from a common array, an XML file, and database.

    Now, let's take a look at the definition of the helper Chart disassembled using Object Browser.

    Listing 2: Definition of the class Chart in Object Browser

    Seen from above, the Chart helper provides strong support for output. As for detailed styled and legend related stuff, there is less support. Hence, you'd better refer to the ASP.NET Chart control related sub controls to get yourselves quickly familiar with the Chart helper.

    Sample 1

    Let's now look at a simple case in using the Chart helper. The sample ASP.NET MVC 3 project here is called MVC3ChartTest.

    First, let's create a controller named ChartsController, as shown below.

    Next, right click the action BasicChart to create a non-strongly-typed view data and non-master page supported view with the same name. After that, alter its content with the following.

    Please note the code block inside the second @{} where we instantiated the Chart helper with two simple parameters. Note the subsequent three methods – AddTitle, AddSeries and Write related calling is something special, isn't it? No semicolon at the end of each statement! This is helper specific simplified method call syntax.

    Obviously, this example exhibits to you a non-real case - we've provided data directly from inside the view. Another point worth noticing is the Write method. Let's say nothing but look at its definition first:

    Till now, I would not say anything. If you are familiar with the BinaryWrite method and traditional ASP.NET image rendering approaches, then you have got the answer.

    Next, let's look at the running-time snapshot, as shown in Figure 3 below.

    Figure 3: A simple Column Chart in action

    A simple Column Chart in action

    Cute readers may find that in the above figure, the layout page (master page) related stuff has not appeared. In fact, this can be easily achieved in another view named BasicChartWithMasterPage.

    Obviously, the key above lies in the line below:

    It's also easy to comprehend. Have seen the following in your former ASP.NET programming experience?

    So, you've got the right answer – all the inner workings are quite similar.

    Next, let's look at the running-time snapshot, as shown in Figure 4 below.

    Figure 4: A Column Chart with the Master page

    A Column Chart with the Master page

    Sample 2

    In this section, we are going to research into another example with the Chart helper which is very close to reality.

    1. Set up Model

    As with the case in the WebGrid section, we should also set up an ADO.NET Entity model. For this, take the following steps:

    (1) Open the sample project MVC3ChartTest. Under the folder Models, create a model file named NorthwindModel.edmx.

    (2) Remember in the related "Choose Your Database Objects" dialog box Select the view Category_Sales_for_1997 and ensure that the value of the Model namespace is NorthwindModel.

    (3) Right click the Models folder to create a higher-layer model class named NorthModel. Below is the main code of this model.

    First, note the view Category_Sales_for_1997 (from the classical database Northwind) is a simple view including only two fields – CategoryName (of string type) and CategorySales (of decimal type). Here it becomes an entity related to this view. Figure 5 illustrates its related schema in the .edmx designer.

    Figure 5: The schema of the view Category_Sales_for_1997

    The schema of the view Category_Sales_for_1997

    Second, we create an only public property PieChart of type Chart. By invoking another helper method BuildServerPieChart, we want the property to return a Chart type which both serves the controller action and related view.

    Third, to simplify the programming, we've created a helper class PieChartData.

    Now, let's look at the helper method BuildServerPieChart related coding.

    Apparently, the core of the above code is mainly around another method BindChartData. Please notice that how we set up the instance of the helper Chart, call its related methods, and specifies the pie type of chart related properties.

    2. Create the action method

    With the model in hand, now it's time for us to create a relevant action. For simplicity, we utilized the default controller HomeController, inside which we created the action Index.

    Now, the above code is easy to understand. The action returns a view named Index, with the instantiation of the model class NorthModel as the parameter.

    3. Create the view

    Right click the above action Index and add a new view with the default name Index. Note we should select the strongly-typed class MVC3ChartTest.Models.NorthModel as the view model. The final appearance of the view Index looks like this:

    As introduced in the article "Experience ASP.NET MVC 3 Beta -the Razor View Engine", the @model directive is a good invention of ASP.NET MVC 3 Beta which greatly helps to simplify the model invocation.

    Now, the focus shifts to the following line:

    Since we've leveraged the strongly-typed class invocation ahead of time, the Model property here should refer to the instance of the model class NorthModel. Easily seen, here the public property PieChart of the model related method Write is called, as a result of which the pie chart will be rendered on the client-side screen. Figure 6 indicates the related running-time snapshot.

    Figure 6: The Pie Chart gets rendered

    The Pie Chart gets rendered

    Summary

    This article shows you the elementary usage of the two newly-introduced helpers, WebGrid and Chart, in ASP.NET MVC 3 Beta with relevant examples. As pointed out in the article, we've scratched the surface of the two helpers - there are still numerous properties and methods worthy to be deeply delved into. In the next installment, we are going to introduce the other three important helpers - Crypto, WebImage, and WebMail.

    The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    jQuery Mobile Pages
    Brian Mains explains how to create pages with the jQuery Mobile framework.

    You might also be interested in the following related blog posts


    Introducing SharePoint 2010 Training at U2U read more
    12 ASP.NET MVC Best Practices read more
    The Telerik CAB Enabling Kit and SCSF - Tutorial 5: The RadPanelBar UIExtensionSite read more
    MvcContrib working on Portable Areas read more
    Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 25: ViewModel read more
    Default Templated Views read more
    Telerik Announces Support for Microsoft Silverlight 3 read more
    Going Controller-less in MVC: The Way Fowler Meant It To Be read more
    Afternoon of ASP.NET MVC [16 June] (free Headspring event) read more
    ASP.NET MVC and the templated partial view (death to ASCX) read more
    Top
     
     
     

    Please login to rate or to leave a comment.

    Free Agile Project Management Tool from Telerik
    TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.