Binding Data to Silverlight 4.0 Controls Using ASP.NET MVC Framework 2.0

Introduction

Silverlight is a browser plugin that promotes a collaborative development environment of rich online media content that enables developers and designers alike to integrate multimedia and graphics into web pages within the context of the managed environment of Microsoft .NET framework. Over the past few years, Silverlight, formerly known as Windows Presentation Foundation (WPF), has quickly become the technology of choice for developing the next generation of cross-browser, cross-platform Rich Internet Applications (RIAs). ASP.NET MVC Framework is a platform that enables you to design and implement applications that are based on the MVC design pattern. This article takes a look at how ASP.NET MVC Framework 2.0 applications can be used to bind data to Silverlight 4.0 data controls.

Pre-requisites

To execute the code examples illustrated in this article, you should have the following installed in your system:

  • ASP.NET MVC 2.0
  • Microsoft Visual Studio 2008

Alternatively, you can have Microsoft Visual Studio 2010 installed in your system--you'll get the ASP.NET MVC Framework and the necessary templates you need to work embedded there.

Before we delve deep into implementing an application that would demonstrate how to integrate Silverlight 4.0 and ASP.NET MVC Framework 2.0, let's take a quick tour of a few basic concepts.

What is the ASP.NET MVC Framework?

The ASP.NET MVC Framework is based on the proven time tested Model View Controller (MVC) Design Pattern and provides you a platform for designing and implementing web applications where you can have a cleaner separation of concerns, better code organization, seamless extensibility, scalability and code reuse. Applications designed using the ASP.NET MVC Framework is easier to test and maintain. The Model View Controller Design Pattern comprises mainly of three components: the model to store the data and business components of the application, the view to present data to the user and the controller to integrate all the components nicely.

Implementing a Sample Application

In this section we will implement a sample application that would use Silverlight 4.0 to present data to the user in a data grid. When you create a new Silverlight project, you have the option of choosing ASP.NET MVC as its host.The Silverlight 4.0 application will use an ASP.NET MVC 2.0 application as its host. In essence, Json data returned from the ASP.NET MVC application will be data bound to a Silverlight 4.0 data grid.

In this example we will make use of the AdventureWorks sample database for SQL Server 2008. To implement an application that uses ASP.NET MVC 2.0 to bind data to a Silverlight 4.0 data grid, follow these steps:

  1. Open Visual Studio 2008/2010 IDE
  2. Click on File -> New -> Project
  3. Select Silverlight Application from the list of the project templates displayed

    A list of the project templates displayed, choose Silverlight
    Figure 1

  4. Select ASP.NET MVC Web Project as a host for the Silverlight application

    This screenshot shows where Select ASP.NET MVC Web Project as a host for the Silverlight application
    Figure 2

  5. Refrain from creating a Unit Test Project as we wouldn't be discussing anything on how we can do unit tests in this article

    Refrain from creating a Unit Test Project
    Figure 3

    Here's how the Solution Explorer would look like:

    The Solution Explorer should look like this
    Figure 4

  6. Right-click on the models folder in the ASP.NET MVC web project and select LINQ to SQL classes to create a data context for the AdventureWorks database
  7.  ASP.NET MVC web project and select LINQ to SQL classes
    Figure 5

  8. Create a new Controller class and name it as CustomerController. Paste the following code for the List action method into this class:
  9.            public ActionResult List()
               {
                   MyDataClassesDataContext dataContext = new MyDataClassesDataContext();
                   var customers = from c in dataContext.Customers
                              select new
                              {
                                  c.CustomerID,
                                  c.AccountNumber
                              };
                   return Json(customers,JsonRequestBehavior.AllowGet);
               }
     



Binding Data to Silverlight 4.0 Controls Using ASP.NET MVC Framework 2.0

The JsonRequestBehavior.AllowGet Property

Notice the usage of JsonRequestBehavior.AllowGet property. You should use this property while returning Json data to ensure from your ASP.NET MVC application. If this property is not set while returning Json data, you would encounter the following error while you execute a Json request: "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet." The reason for this error is that Json data is blocked for GET requests in MVC 2.0 for security reasons.

The following code example illustrates how you can use the JsonRequestBehavior.AllowGet property:

   var data = (from s in student.GetStudentData()   
               select s).ToArray<Student>();   
               return Json(data, JsonRequestBehavior.AllowGet); 
 

Making an Asynchronous Call

In your Silverlight application, all you need to do is invoke the URL in an asynchronous call as shown in the code snippet below:

  WebClient mvc = new WebClient();
  mvc.OpenReadCompleted += new OpenReadCompletedEventHandler(mvc_OpenReadCompleted);
  mvc.OpenReadAsync(new Uri("http://localhost:1570/Customer/List"));

Here's how the Json data that is returned can be bound to the data grid in Silverlight:

   void mvc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
           {
               DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<Customer>));
               List<Customer> customers = (List<Customer>)json.ReadObject(e.Result);
               gridCustomer.DataContext = customers;
           }
 

You would also need the customer class to map the data that would be returned as Json:

       public class Customer
       {
           public int CustomerID { get; set; }
           public string AccountNumber { get; set; }
       }
 

The Complete Source Code

Here is how the complete source code of the CustomerController class would look:

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  using MySilverlightApplication.Web.Models;
  
  namespace MySilverlightApplication.Web.Controllers
  {
      public class CustomerController : Controller
      {
          public ActionResult Index()
          {
              return View();
          }
  
          public ActionResult List()
          {
              MyDataClassesDataContext dataContext = new MyDataClassesDataContext();
              var customers = from c in dataContext.Customers
                         select new
                         {
                             c.CustomerID,
                             c.AccountNumber
                         };
              return Json(customers,JsonRequestBehavior.AllowGet);
          }
      }
  }

Here is how the complete source code of MainPage.xaml.cs file would look:

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Net;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Documents;
  using System.Windows.Input;
  using System.Windows.Media;
  using System.Windows.Media.Animation;
  using System.Windows.Shapes;
  using System.Runtime.Serialization.Json;
  
  namespace MySilverlightApplication
  {
      public partial class MainPage : UserControl
      {
          public MainPage()
          {
              InitializeComponent();
              Loaded += new RoutedEventHandler(Page_Loaded);
          }
  
          void Page_Loaded(object sender, RoutedEventArgs e)
          {
              WebClient mvc = new WebClient();
              mvc.OpenReadCompleted += new OpenReadCompletedEventHandler(mvc_OpenReadCompleted);
              mvc.OpenReadAsync(new Uri("http://localhost:1570/Customer/List"));
          }
  
          void mvc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
          {
              DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<Customer>));
              List<Customer> customers = (List<Customer>)json.ReadObject(e.Result);
              gridCustomer.DataContext = customers;
          }
      }
  
      public class Customer
      {
          public int CustomerID { get; set; }
          public string AccountNumber { get; set; }
      }
  }

Suggested Readings

http://www.asp.net/mvc
http://dotnetslackers.com/articles/aspnet/a-first-look-at-asp-net-mvc-2.aspx
http://msdn.microsoft.com/en-us/library/ee728598(v=VS.100).aspx

Summary

Scott Guthrie states in his blog: "One of the benefits of using an MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated."

Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/aspnet-mvc-framework.aspx.

This article presented how ASP.NET MVC Framework can be integrated with Silverlight and how data can be bound to the Silverlight data controls. The view simply contained a Silverlight data grid that would was used to bind the Json data retrieved from the Customer table of the AdventureWorks database. This Json data was returned though the usage of ASP.NET MVC Framework 2.0.

Related Articles



About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing)

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • This paper introduces IBM Java on the IBM PowerLinux 7R2 server and describes IBM's implementation of the Java platform, which includes IBM's Java Virtual Machine and development toolkit.

  • Targeted attacks and advanced threats are customized to infiltrate your unique IT infrastructure, evade conventional defenses, and remain hidden while stealing your corporate data. To detect these criminal intrusions, analysts and security experts agree that organizations should deploy advanced threat protection as part of an expanded security monitoring strategy. For this comparative analysis of breach detection systems, product analysis reports and comparative analysis reports are used to create the security …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds