Wednesday, June 22, 2011

Passing parameters between Silverlight and ASP.NET – Part 1

While working with Silverlight applications, we may face some scenarios where we may need to embed Silverlight as a component, like for e.g in Sharepoint Webpars or simple we can have the same with ASP.NET. The biggest challenge comes when we have to pass the parameters from ASP.NET to Silverlight components or back from Silverlight to ASP.NET.

We have lots of ways we can do this, like using InitParams, QueryStrings, using HTML objects in Silverlight, etc. All these different techniques have some advantages or disadvantages or limitations. Lets see one by one why we should choose one and what are the ways to achieve the same.

1. InitParams:

Lets start with InitParams, Start your Visual Studio 2010 IDE, and Create a Silverlight Application, give any name. Now go to the ASP.NET WebProject which is used to Host the Silverlight XAP component. You will find lots of different tags are used by Silverlight object as <params> tags. To use InitParams, Silverlight provides us with a tag called InitParams which we can use to pass parameters to Silverlight object from ASP.NET.

   1: <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
   2:   <param name="source" value="ClientBin/SilverlightApp.xap"/>
   3:   <param name="onError" value="onSilverlightError" />
   4:   <param name="background" value="white" />
   5:   <param name="minRuntimeVersion" value="4.0.50826.0" />
   6:   <param name="initparams" id="initParams" runat="server" value=""/>
   7:   <param name="autoUpgrade" value="true" />
   8:   <a href="" style="text-decoration:none">
   9:        <img src="" alt="Get Microsoft Silverlight" style="border-style:none"/>
  10:   </a>
  11: </object>
Here in the code above I have included a initParam as a param tag (line 6), now in the page load I will add a line
   1: initParams.Attributes.Add("value", "key1=Brij, key2=Mohan");

This basically add a value parameter inside the initParam. So that's all we need in our ASP.NET side, now coming to the Silverlight Code open the code behind of App.xaml and add the following lines of code.

   1: private string firstKey, secondKey;
   2: private void Application_Startup(object sender, StartupEventArgs e)
   3: {
   4:     if (e.InitParams.ContainsKey("key1"))
   5:         this.firstKey = e.InitParams["key1"];
   6:     if (e.InitParams.ContainsKey("key2"))
   7:         this.secondKey = e.InitParams["key2"];
   8:     this.RootVisual = new MainPage(firstKey, secondKey);
   9: }

This code fetch the init params and pass it to our MainPage.xaml constructor, in the MainPage.xaml we can use these variables according to our requirement, here in this example I am simply displaying the variables in a Message Box.

   1: public MainPage(string param1, string param2)
   2: {
   3:     InitializeComponent();
   4:     MessageBox.Show("Welcome, " + param1 + " " + param2);
   5: }
imageThis will give you a sample output as

Limitations: Depending on the browsers you have some limitation on the overall string length of the parameters you can pass. To get more details on this limitation, you can refer to this link :

2. QueryStrings

To show this example I am taking the scenario where we have a default.aspx page and we are going to the SIlverlightTestPage.aspx, and we have to work with the parameters which was passed by default.aspx in the SilverlightTestPage.aspx Silverlight Component.

So first I will add a new page in my application which contains a button with ID =btnNext, and on click of the button I will redirect my page to my SilverlightTestAppPage.aspx with the required query strings.

Code of Default.aspx

   1: protected void btnNext_Click(object sender, EventArgs e)
   2: {
   3:     Response.Redirect("~/SilverlightAppTestPage.aspx?FName=Brij" + "&LName=Mohan");
   4: }

Code of MainPage.xaml.cs

   1: public partial class MainPage : UserControl
   2: {
   3:     public MainPage()
   4:     {
   5:         InitializeComponent();
   6:         this.Loaded += new RoutedEventHandler(MainPage_Loaded);
   7:     }
   9:     void MainPage_Loaded(object sender, RoutedEventArgs e)
  10:     {
  11:         IDictionary<string, string> qString = HtmlPage.Document.QueryString;
  12:         string firstName = string.Empty;
  13:         string lastName = string.Empty;
  14:         foreach (KeyValuePair<string, string> keyValuePair in qString)
  15:         {
  16:             string key = keyValuePair.Key;
  17:             string value = keyValuePair.Value;
  18:             if (key == "FName")
  19:                 firstName = value;
  20:             else if (key == "LName")
  21:                 lastName = value;
  22:         }
  23:         MessageBox.Show("Welcome, " + firstName + " " + lastName);
  24:     }
  25: }

Set the Start-up page as Default.aspx, now run the application. This will give you the following output:

imageSince here also you are using the Query Strings to pass your parameters, so you are depending on the browser capabilities of the length of the query strings it can pass. Here also you can refer the limitation which I have mentioned in my previous example for the length of parameters you can use.


3. Using HtmlPage.Document

Silverlight to ASP.NET <—> ASP.NET to Silverlight: To show this I setup a sample Silverlight Application with Buttons Get Data and Set Data with the Data Text Box. In ASP.NET page I keep a TextBox to Show how the values passed to and From Silverlight to ASP.NET reflects back. My page with Silverlight control looks like this.


When I Say Get Data it pulls the data from ASP.NET to Silverlight Control Text Box, and When I say Set data it basically Set the Value from Silverlight Control TextBox to ASP.NET TextBox. Now let see the code how it is doing.

This is my ASP.NET Source Code. Here I have just created a TextBox named : txtData

   1: <body>
   2:     <form id="form1" runat="server" style="height:100%">
   3:     <div id="silverlightControlHost">
   4:     ASP.NET TextBox:  <input type="text" runat="server" id="txtData" value="Some Data" />
   5:         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
   6:           <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
   7:           <param name="onError" value="onSilverlightError" />
   8:           <param name="background" value="white" />
   9:           <param name="minRuntimeVersion" value="4.0.50826.0" />
  10:           <param name="autoUpgrade" value="true" />
  11:           <a href="" style="text-decoration:none">
  12:                <img src="" alt="Get Microsoft Silverlight" style="border-style:none"/>
  13:           </a>
  14:         </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
  15:         </div>
  16:     </form>
  17: </body>

My actual logic for getting and setting the data lies in my Silverlight Control, this is my XAML code with TextBox and Buttons.

   1: <Grid x:Name="LayoutRoot" Background="White" Height="100" Width="450" VerticalAlignment="Top">
   2:     <Grid.ColumnDefinitions>
   3:         <ColumnDefinition Width="110" />
   4:         <ColumnDefinition Width="110" />
   5:         <ColumnDefinition Width="110" />
   6:         <ColumnDefinition Width="110" />
   7:     </Grid.ColumnDefinitions>
   8:     <TextBlock Text="Silverlight Text Box: " Grid.Column="0" VerticalAlignment="Center"></TextBlock>
   9:     <TextBox x:Name="DataText" Width="100" Grid.Column="1" Height="20"></TextBox>
  10:     <Button x:Name="GetData" Width="100" Click="GetData_Click" Grid.Column="2" Height="30" Content="Get Data"></Button>
  11:     <Button x:Name="SetData" Width="100" Click="SetData_Click" Grid.Column="3" Height="30" Content="Set Data"></Button>
  12: </Grid>

Now we have to write few lines of Button Events for Get Data and Set Data which basically make use of Windows.System.Browser namespace.

   1: private void GetData_Click(object sender, RoutedEventArgs e)
   2: {
   3:     DataText.Text = HtmlPage.Document.GetElementById("txtData").GetProperty("value").ToString();
   4: }
   6: private void SetData_Click(object sender, RoutedEventArgs e)
   7: {
   8:     HtmlPage.Document.GetElementById("txtData").SetProperty("value", DataText.Text);
   9: }

That’s it so when we run this application my Form will look like this.


4. Using Object Serialization.

This is a useful when we want to pass Objects of Data from our ASP.NET application to Silverlight Controls and back. This basically uses the above technique I mentioned in Part 3 above. Since this itself is a lengthy topic so details of this I am going to cover in Part 2 of this Post with Sample Code Example very soon.


Anonymous said...

Thanks a lot man.....

Anonymous said...

This was really useful, I had been wondering if I could ever come out of this confusion. Thanks a lot...

Anonymous said...

Helped a lot dude!
Nowhere else I found the codebehind way of adding initparameters...
common sense!

Santosh said...

Thanks a Lot man, its valuable tip

SteveC said...

Excellent post, helped me a lot developer said...
This comment has been removed by a blog administrator.
Anonymous said...

Thanks for providing such a nice info...
but i am not able to get any value from initParams in App() page in silverlight.

I added one value in aspx, as u mentioned in (1. InitParams), but i am not getting that value any where...

Kindly help me in the same.. Thanks in advance...

Anonymous said...

now in the page load I will add a line

Hi Im very new to SL..
Can you please tell me where can i find my Page load

Anonymous said...

my email id is
can you please send me a sample project
I cant find that page load

Brij said...

You dont have page load event in Silverlight, page load is something which you will find in, To perform any suce initialization tasks you may use Initialize event in Silverlight.

Please refer the following links to get a better understanding of SIlverlight related concepts:

Anonymous said...

Is there any way instead of passing text or setting text from silverlight can i pass byte array or can i access byte array property from silverligt to webpage..

Basically in my situation i need to pass the byte array "byte[]" from silverlight app to .net app

lingmaaki said... parameter passing


Post a Comment