Silver Light with 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 -> Silver Light


Step 2
To hosting SILVERLIGHT 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.
Step 3

Right click on Controller. Click on Add-> New Item and select add LINQ to SQL classes. Give a name.
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.

Now give a Server name and select database to connect
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. Now if you click on Test.Dbml.CS file. You will find code has been created for you.Up to this step, Linq class has been created.

Step 5

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. 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 6
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.


List.aspx will have following code. 

<%@ Page
Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>

<title>List</title>

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

<h2>List</h2>

</asp:Content>

 Remove
<h2>List</h2>
And add below code

<p><object data=””data:application/x-silverlight-2type=”application/x-silverlight-2″
width=”300px” height=”300px”>
<param name=”source” value=”/ClientBin/SilverLightMvcTest.xap/>
<param name=”minRuntimeVersion” value=”2.0.31005.0″
/>
<param name=”windowless” value=”true”
/>
<param name=”Background” value=”#00FFFFFF”
/>
</object>
</p>

 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” %>
 <asp:Content ID=”Content1″ ContentPlaceHolderID=”head” runat=”server”>

<title>List</title>

</asp:Content

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

 <p>

<object data=””data:application/x-silverlight-2type=”application/x-silverlight-2″ width=”300px” height=”300px”>

<param name=”source” value=”/ClientBin/SilverLightMvcTest.xap” />

<param name=”minRuntimeVersion” value=”2.0.31005.0″ />

<param name=”windowless” value=”true” />

<param name=”Background” value=”#00FFFFFF” />

</object>

</p>

 </asp:Content>

 Step 8

Page.Xaml.cs

<UserControl
x:Class=”SilverLightMvcTest.Page”xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

xmlns:data=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”

Width=”400″ Height=”300″>

<Grid x:Name=”LayoutRoot” Background=”White”>

<Grid.RowDefinitions>

<RowDefinition Height=”Auto” />

<RowDefinition Height=”Auto” />

</Grid.RowDefinitions>    

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”Auto” />

 

</Grid.ColumnDefinitions>

<Button x:Name=”b1″ Height=”100″ Width=”100″ Click=”b1_Click” Grid.Row=”0″ Grid.Column=”1″/>
<data:DataGrid x:Name=”MyGrid” Grid.Row=”1″ Grid.Column=”1″>
</data:DataGrid>
</Grid> </UserControl>

<ColumnDefinition Width=”Auto” />

 Step 9
Right click on SilverLight Project and add new class . Give it name Test_Details.Add following code in Test_Details.cs

Test_Details.cs

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.

Step 11

  1. Add a reference to System.RunTime.Serilization and System.ServiceModel.Web to SilverLight Project.
  2. Include namespace

    using System.Runtime.Serialization.Json to Page.Xaml.Cs

     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 += newOpenReadCompletedEventHandler(_client_OpenReadCompleted);

client.OpenReadAsync(newUri(http://localhost:2675/home/list&#8221;)); }

 void _client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)

{

DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<Test_Details>));

 IList<Test_Details> res = (List<Test_Details>)(json.ReadObject(e.Result));

 MyGrid.ItemsSource = res;

} } }

Run the application.

2 responses to “Silver Light with ASP.Net MVC Framework”

  1. Hi,

    I wanted to find out if you can help me solve this issue

    here is what i want to achieve

    I am using northwind database region table

    on my mainpage.xaml I have an autocomplete box which wheen i type in regionid , 1 .. it shows me 1 , 13 , 113 records and once i select the record I want
    I want to add the row in this case regionid and regiondescription to another table , how do i go about doing this
    *****************************************************
    my Mainpage.xaml

    Mainpage.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 Autocomplete.Web;
    using System.ServiceModel.DomainServices.Client;

    namespace Autocomplete
    {
    public partial class MainPage : UserControl
    {
    public MainPage()
    {
    InitializeComponent();
    Loaded +=new RoutedEventHandler(MainPage_Loaded);
    List cities = new List();
    cities.Add(“London”);
    cities.Add(“Seattle”);
    cities.Add(“Tokyo”);
    cities.Add(“Nairobi”);
    cities.Add(“Lisbon”);
    cities.Add(“New York”);
    cities.Add(“Paris”);
    cities.Add(“San Francisco”);
    autoCompleteBox1.ItemsSource = cities;
    Region r1 = new Region();

    // textBlock1.Text = autoCompleteBox1.SelectedItem;
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
    DomainService100 datacontext = new DomainService100();
    LoadOperation reg = datacontext.Load(datacontext.GetRegionsQuery());
    autoCompleteBox2.ItemsSource = reg.Entities;

    // txtSearchBox.Populating +=new PopulatingEventHandler(txtSearchBox_Populating);

    }

    private void txtSearchBox_Populating(object sender, PopulatingEventArgs e)
    {

    }

    private void regionDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
    {

    if (e.HasError)
    {
    System.Windows.MessageBox.Show(e.Error.ToString(), “Load Error”, System.Windows.MessageBoxButton.OK);
    e.MarkErrorAsHandled();
    }
    }

    private void filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    DomainService100 datacontext = new DomainService100();
    Region RegionObject = new Region();
    datacontext.Regions.Add(RegionObject);
    // dataGrid1.ItemsSource = RegionObject;

    insert into a new table regionview regionid and regiondescription

    }

    }
    }

  2. I wanted to email you as I have not gotten any answer after posting on silverlight forums
    http://forums.silverlight.net/forums/t/225480.aspx

    here is what i want to achieve

    I am using northwind database region table

    on my mainpage.xaml I have an autocomplete box which wheen i type in regionid , 1 .. it shows me 1 , 13 , 113 records and once i select the record I want
    I want to add the row in this case regionid and regiondescription to another table , how do i go about doing this
    *****************************************************
    my Mainpage.xaml

    Mainpage.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 Autocomplete.Web;
    using System.ServiceModel.DomainServices.Client;

    namespace Autocomplete
    {
    public partial class MainPage : UserControl
    {
    public MainPage()
    {
    InitializeComponent();
    Loaded +=new RoutedEventHandler(MainPage_Loaded);
    List cities = new List();
    cities.Add(“London”);
    cities.Add(“Seattle”);
    cities.Add(“Tokyo”);
    cities.Add(“Nairobi”);
    cities.Add(“Lisbon”);
    cities.Add(“New York”);
    cities.Add(“Paris”);
    cities.Add(“San Francisco”);
    autoCompleteBox1.ItemsSource = cities;
    Region r1 = new Region();

    // textBlock1.Text = autoCompleteBox1.SelectedItem;
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
    DomainService100 datacontext = new DomainService100();
    LoadOperation reg = datacontext.Load(datacontext.GetRegionsQuery());
    autoCompleteBox2.ItemsSource = reg.Entities;

    // txtSearchBox.Populating +=new PopulatingEventHandler(txtSearchBox_Populating);

    }

    private void txtSearchBox_Populating(object sender, PopulatingEventArgs e)
    {

    }

    private void regionDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
    {

    if (e.HasError)
    {
    System.Windows.MessageBox.Show(e.Error.ToString(), “Load Error”, System.Windows.MessageBoxButton.OK);
    e.MarkErrorAsHandled();
    }
    }

    private void filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    DomainService100 datacontext = new DomainService100();
    Region RegionObject = new Region();
    datacontext.Regions.Add(RegionObject);
    // dataGrid1.ItemsSource = RegionObject;

    insert into a new table regionview regionid and regiondescription

    }

    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com