Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Passing parameters between Silverlight and ASP.NET – Part 1

, 31 Jul 2011
Rate this:
Please Sign up or sign in to vote.
A description of how to embed Silverlight components in ASP.NET and pass parameters to them

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

<object data="data:application/x-silverlight-2," 
      type="application/x-silverlight-2" width="100%" height="100%">
  <param name="source" value="ClientBin/SilverlightApp.xap"/>
  <param name="onError" value="onSilverlightError" />
  <param name="background" value="white" />
  <param name="minRuntimeVersion" value="4.0.50826.0" />
  <param name="initparams" id="initParams" runat="server" value=""/>
  <param name="autoUpgrade" value="true" />
  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" 
            style="text-decoration:none">
       <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
          alt="Get Microsoft Silverlight" style="border-style:none"/>
  </a>
</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

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.

private string firstKey, secondKey;
private void Application_Startup(object sender, StartupEventArgs e)
{
    if (e.InitParams.ContainsKey("key1"))
        this.firstKey = e.InitParams["key1"];
    if (e.InitParams.ContainsKey("key2"))
        this.secondKey = e.InitParams["key2"];
    this.RootVisual = new MainPage(firstKey, secondKey);
}

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.

public MainPage(string param1, string param2)
{
    InitializeComponent();
    MessageBox.Show("Welcome, " + param1 + " " + param2);
}

This will give you a sample output as

image

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 :http://www.boutell.com/newfaq/misc/urllength.html

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

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

Code of MainPage.xaml.cs

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    }
 
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        IDictionary<string, string> qString = HtmlPage.Document.QueryString;
        string firstName = string.Empty;
        string lastName = string.Empty;
        foreach (KeyValuePair<string, string> keyValuePair in qString)
        {
            string key = keyValuePair.Key;
            string value = keyValuePair.Value;
            if (key == "FName")
                firstName = value;
            else if (key == "LName")
                lastName = value;
        }
        MessageBox.Show("Welcome, " + firstName + " " + lastName);
    }
}

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

image

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

image

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

<body>
    <form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
    ASP.NET TextBox:  <input type="text" runat="server" 
                             id="txtData" value="Some Data" />
        <object data="data:application/x-silverlight-2," 
             type="application/x-silverlight-2" width="100%" 
             height="100%">
          <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" 
                       style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
                 alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" 
          style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
        </div>
    </form>
</body>

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

<Grid x:Name="LayoutRoot" Background="White" 
       Height="100" Width="450" VerticalAlignment="Top">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="110" />
    </Grid.ColumnDefinitions>
    <TextBlock Text="Silverlight Text Box: " Grid.Column="0" 
      VerticalAlignment="Center"></TextBlock>
    <TextBox x:Name="DataText" Width="100" 
      Grid.Column="1" Height="20"></TextBox>
    <Button x:Name="GetData" Width="100" Click="GetData_Click" 
      Grid.Column="2" Height="30" Content="Get Data"></Button>
    <Button x:Name="SetData" Width="100" Click="SetData_Click" 
      Grid.Column="3" Height="30" Content="Set Data"></Button>
</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.

private void GetData_Click(object sender, RoutedEventArgs e)
{
    DataText.Text = HtmlPage.Document.GetElementById(
      "txtData").GetProperty("value").ToString();
}
 
private void SetData_Click(object sender, RoutedEventArgs e)
{
    HtmlPage.Document.GetElementById(
      "txtData").SetProperty("value", DataText.Text);
}

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

image

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brij M
Technical Lead Mphasis Limited
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
QuestionHow to invoke asp.net function from silver light Pinmembervinodvc5@yahoo.com23-Feb-12 20:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 31 Jul 2011
Article Copyright 2011 by Brij M
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid