.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> Silverlight >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Silverlight in ASP.Net MVC Framework: Tutorial

Posted By:Dhananjay Kumar       Posted Date: February 25, 2010    Points: 25    Category: Silverlight    URL: http://www.dotnetspark.com  

Silverlight in ASP.Net MVC Framework. This tutorial demonstrates how to fetch data using LINQ and display it it a Silverlight application using ASP.NET MVC Framework.
 

Objective:

In this tutorial we will fetch data from SQL Server database using LINQ and display that data in Silver Light, while we are following ASP.Net MVC Framework.

Step 1:


Create a Silver Light application.

File -->New-->  Project--> SilverLight

Give a meaningful name. Here name is SilverLightinMVCFramework.

1.gif
 
Step 2:

Hosting Silver Light application.

There are three options available for hosting a Silver Light application.  Select ASP.Net MVC Web project.  Then after ,Select option NO for creating UNIT Test Project.

2.gif

3.gif

Now a SilverLight application with ASP.Net MVC host web project. 

Solution  Explorer should look like below.

4.gif

Step 3:


Right click on Controller. Click on Add-> New Item and select add LINQ to SQL classes. Give a name, here name is Test.dbml

5.gif

Step 4:

Here, I have already created a TEST data base in my database.  I am going to display data from this database.
  1. Open Server Explorer 
  2. Right click on  Data Connection 
  3. Click Add New Data Connection.
Below screen will get display.

6.gif
 
Now give a Server name and select database to connect. In my case name of database is Test.

7.gif

Expand test.dbo. Here there are 2 tables in Test database.  One is Test_Details and other is testsample.  In this tutorial, I am going to display data from Test_Detatils table. So select this table from Server explorer and drag it on Test.dbml page.

8.gif
9.gif

Now if you click on Test.Dbml.CS file. You will find code has been created for you. Code is as follows. You don't need to write this code. It has been already created once you drag table from server explorer to Test.Dbml page.

Test.Dbml.CS

#pragma warning disable 1591 
//------------------------------------------------------------------------------ 
//  
//  This code was generated by a tool. 
//  Runtime Version:2.0.50727.3053 
// 
//  Changes to this file may cause incorrect behavior and will be lost if 
//  the code is regenerated. 
//  
//------------------------------------------------------------------------------ 
 

namespace SilverLightMvcTest.Web.Models 
{ 
  using System.Data.Linq; 
  using System.Data.Linq.Mapping; 
  using System.Data; 
  using System.Collections.Generic; 
  using System.Reflection; 
  using System.Linq; 
  using System.Linq.Expressions; 
  using System.ComponentModel; 
  using System; 
  
  
  [System.Data.Linq.Mapping.DatabaseAttribute(Name="test")] 
  public partial class TestDataContext : System.Data.Linq.DataContext 
  { 
  
  private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); 
  
  #region Extensibility Method Definitions 
  partial void OnCreated(); 
  #endregion 
  
  public TestDataContext() : 
    base(global::System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString, mappingSource) 
  { 
  OnCreated(); 
  } 
  
  public TestDataContext(string connection) : 
  base(connection, mappingSource) 
  { 
  OnCreated(); 
  } 
  
  public TestDataContext(System.Data.IDbConnection connection) : 
  base(connection, mappingSource) 
  { 
  OnCreated(); 
  } 
  
  public TestDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource) 
  { 
  OnCreated(); 
  } 
  
  public TestDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource) 
  { 
  OnCreated(); 
  } 
  
  public System.Data.Linq.Table Test_Details 
  { 
  get 
  { 
  return this.GetTable(); 
  } 
  } 
  } 
  
  [Table(Name="dbo.Test_Details")] 
  public partial class Test_Detail 
  { 
  
  private string _testId; 
  
  private string _testName; 
  
  private int _testMaxMarks; 
  
  public Test_Detail() 
  { 
  } 
  
  [Column(Storage="_testId", DbType="NVarChar(50) NOT NULL", CanBeNull=false)] 
  public string testId 
  { 
  get 
  { 
  return this._testId; 
  } 
  set 
  { 
  if ((this._testId != value)) 
  { 
  this._testId = value; 
  } 
  } 
  } 
  
  [Column(Storage="_testName", DbType="NVarChar(50) NOT NULL", CanBeNull=false)] 
  public string testName 
  { 
  get 
  { 
  return this._testName; 
  } 
  set 
  { 
  if ((this._testName != value)) 
  { 
  this._testName = value; 
  } 
  } 
  } 
  
  [Column(Storage="_testMaxMarks", DbType="Int NOT NULL")] 
  public int testMaxMarks 
  { 
  get 
  { 
  return this._testMaxMarks; 
  } 
  set 
  { 
  if ((this._testMaxMarks != value)) 
  { 
  this._testMaxMarks = value; 
  } 
  } 
  } 
  } 
} 
#pragma warning restore 1591

Up to this step, Linq class has been created.

Step 5:

Click on Controller and select HomeController.  You will see code window for HomeController.
Right now this is containing two actions called Index and About.
Note : Methods inside a controller is called action. For details on the same , see other articles.
10.gif 

Step 6:

We will add here one more action called List inside Home Controller. Purpose of this action is to fetch out all records of Test_Details table and return List of records as JSON.
Note : For different return types from Action see other articles.
Add following code  in Home Controller class.  Don't forget to include at the top of HomeController.cs

using SilverLightMvcTest.Web.Models; 
public ActionResult List() 
  { 
  TestDataContext _obj = new TestDataContext(); 
  var _res = from r in _obj.Test_Details 
  select r; 
  return Json(_res); 

  }


The above action List is returning JSON of all the records fetch from Test_Dtails table of Test Database.
So now the complete code of HomeController.cs will look like ,

HomeController.cs


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using SilverLightMvcTest.Web.Models; 

namespace SilverLightMvcTest.Web.Controllers 
{ 
  [HandleError] 
  public class HomeController : Controller 
  { 
  public ActionResult Index() 
  { 
  ViewData["Message"] = "Welcome to ASP.NET MVC!"; 

  return View(); 
  } 

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

  public ActionResult List() 
  { 
  TestDataContext _obj = new TestDataContext(); 
  var _res = from r in _obj.Test_Details 
  select r; 
  return Json(_res); 

  } 
  } 
}


Step 7:

Now click on

View --> Home --> Right Click --> Add  View

Give name of the View exactly of action name.  Here action name is List so name of view will be List.  Leave other things as default and click on Add. It will create a List.aspx page.

11.gif
 
List.aspx will have following code.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
 

 
  List 
 
 

 
 

  

List


Remove

  <h2>Listh2>

And add below code 


 



Here at value property of source, name is SilverLightMvcTest.xap . Here make sure you are giving the name, which name you gave to your SilverLight Project at Step 1:
So now complete code for List.aspx would be

List.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
 

 
  List 
 
 

 
 

  


Step 8:

12.gif

Copy paste the below code in Page.Xaml.CS file.

 
   
   
   
   
   
   
   
  

Now click on View arrow.gif ToolBox

Drag DataGrid and drop it after Button element of Xaml.  After dragging complete code of Page.xaml.Cs file would be like below

Page.Xaml.cs


 
   
   
   
   
   
   
   
   
   
  

I have given name of DataGrid as MyGrid and for button as b1.

13.gif

Step 9:

Right click on SilverLight Project and add new class . Give it name Test_Details.

14.gif

15.gif 

Add following code in Test_Details.cs

Test_Details.cs

using System; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Ink; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 

namespace SilverLightMvcTest 
{ 
  public class Test_Details 
  { 
  public string testId 
  { 
  get; 
  set; 
  } 
  public string testName 
  { 
  set; 
  get; 
  } 
  public int testMaxMarks 
  { 
  set; 
  get; 
  } 

  } 
}

Make sure here property name and return type is exactly same of the column name and types in table of database.
Step 10:
  1. Run your application, by clicking F5.
  2. Below screen will come 
  3. Click on address bar and type
http://localhost:2675/home/list
Copy this URL.
16.gif

17.gif
Step 11:
  • Add a reference to System.RunTime.Serilization and System.ServiceModel.Web  to SilverLight Project.

     18.gif

  • Include namespace to Page.Xaml.Cs

    using System.Runtime.Serialization.Json; 
  • Add below code
Page.Xaml.CS

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 SilverLightMvcTest 
{ 
  public partial class Page : UserControl 
  { 
  public Page() 
  { 
  InitializeComponent(); 
  } 

  private void b1_Click(object sender, RoutedEventArgs e) 
  { 
  WebClient _client = new WebClient(); 
  _client.OpenReadCompleted += new OpenReadCompletedEventHandler(_client_OpenReadCompleted); 

  _client.OpenReadAsync(new Uri("http://localhost:2675/home/list")); 

  } 

  void _client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
  { 

  DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List)); 
  
  IList res = (List)(json.ReadObject(e.Result)); 

  MyGrid.ItemsSource = res; 

  } 

  } 
}
Point to note in above code is
In line
_client.OpenReadAsync(new Uri("http://localhost:2675/home/list"));
As the parameter of URI, paste that URI which we copied at step 10 C.
Now Run this by pressing F5, you will get the output, when you click on Button.
Output after clicking on Button
19.gif
How to use attached Zip File?

Step 1: Download

Step 2: Unzip

Step 3: create a table in database called Test_Details  with structure explained above

Step 4: see on which port number, Silverlight application is running.

Let , if it is running on port number 2689.
Change the code in  Page.Xaml.Cs file
With
_client.OpenReadAsync(new Uri("http://localhost:2689/home/list"));
It will run..

Happy Coding!

 Subscribe to Articles

     

Further Readings:

Responses
Author: jay         Company URL: http://www.dotnetspark.com
Posted Date: February 25, 2010

fantastic explanation.
Author: alphapapalima         Company URL: http://www.dotnetspark.com
Posted Date: August 18, 2010

Yes, I have implemented something very similiar. The problem I am having is, when you try to save data back to the controller, the controller will not recognize the data unless the object it is decorated with ModelBinder or ActionFilterAttribute. Because these are found in the System.Web.Mvc libraries, I can't use them in my Silverlight project. So I am left having to maintain two class files. One for Silverlight and one for the MVC web project. Have you found a solution for this?

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend