Passing Parameters to Silverlight from the page

It’s fairly easy to pass querystring’s to silverlight.

IDictionary<string, string> queryStrings = System.Windows.Browser.HtmlPage.Document.QueryString;

So, for my example, if a querystring is passed in I grab the values and do the search, else get all and bind to my silverlight datagrid

IDictionary<string, string> queryStrings = System.Windows.Browser.HtmlPage.Document.QueryString; proxy = new One.PilotStatService.PilotStatsServiceClient(); proxy.GetPilotStatsCompleted += new EventHandler<One.PilotStatService.GetPilotStatsCompletedEventArgs>(proxy_GetPilotStatsCompleted); proxy.GetPilotStatsByNameCompleted += new EventHandler<One.PilotStatService.GetPilotStatsByNameCompletedEventArgs>(proxy_GetPilotStatsByNameCompleted); proxy.SavePilotCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_SavePilotCompleted); if (queryStrings.Count > 0 && !string.IsNullOrEmpty(queryStrings["Name"])) proxy.GetPilotStatsByNameAsync(queryStrings["Name"]); else proxy.GetPilotStatsAsync();

An alternative is to pass parameters in from the page controls ‘inputparameters’ collection.  From the aspx silverlight control:

asp:Silverlight ID=”Xaml1″ InitParameters=”Name=JG53″ runat=”server” Source=”~/ClientBin/One.xap” MinimumVersion=”2.0.30523″ Width=”100%” Height=”100%”

In this case, I’ve hardcoded a default value: InitParameters=”Name=JG53″

If you are using the straight html method vs. the aspx control:

<object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"> <param name="source" value="ClientBin/One.xap"/> <param name="onerror" value="onSilverlightError" /> <param name="background" value="white" /> <param name="initParams" value="Name=JG53" /> <a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/> </a> </object>

You capture these values in the silverlight ‘app’ (App.xaml.cs):

private void Application_Startup(object sender, StartupEventArgs e) { string inputParm = e.InitParams["Name"]; this.RootVisual = new Page(inputParm); }

I modified the Page constructor to accept the parameter:

public Page(string inputParam)

So, let’s say I don’t want this hardcoded, ie. I receive the value from a control, etc… with the Silverlight aspx control I can access the inputParameter property.  For example, with a asp:Silverlight control id of ‘Xaml1’:

<script runat="server"> protected void Page_Load(object sender, EventArgs e) { Xaml1.InitParameters = "Name=JG53"; } </script>

A tad off topic, but another interesting feature of Silverlight is the ability to manipulate the html dom within managed code! 

A simple example, building off the above:  Let’s add a simple input html control to the page :

<form id="form1" runat="server" style="height:100%;"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <input id="MyTestBox" type="text" /> <div style="height:100%;"> <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/One.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" /> </div> </form>

The input ‘MyTextBox’ – now, when the control loads  we are setting the InitParameters to ‘Name=JG53’.  Within the Silverlight Page constructor I can access the input box:

HtmlDocument doc = HtmlPage.Document; IDictionary<string, string> queryStrings = doc.QueryString; doc.GetElementById("MyTestBox").SetProperty("value", inputParam);

This obviously offers up a ton of added capability, being able to manipulate the html dom from within managed code!

Finally, to cap this all off, if I want to build a search page, but keep the input box for search parameters within the html vs. inside the silverlight UI (or both), I can access the html from within Silverlight and retrieve values:

HtmlDocument doc = HtmlPage.Document; string test = doc.GetElementById("MyTestBox").GetProperty("value").ToString();

So, I hope this has covered the many options of interfacing with Silverlight!

Advertisements

7 thoughts on “Passing Parameters to Silverlight from the page

  1. Here’s an example using InitParams to send values to a Silverlight control:

    1. The Silverlight control:
    In the Default.Aspx page, I have the following Silverlight control:

    2. Assign parameteres through code:
    In the “Page_Load” for this host page (Default.Aspx), two Key-Value pairs are being assigned through “InitParameters”:

    slvTest01.InitParameters = “TheValue1=something,TheValue2=321”;

    3. Define properties for the Silverlight control:
    Inside “Page.xaml.cs”, two properties are defined:

    #region The Properties
    public String TheValue1 {get;set;}
    public String TheValue2 {get;set;}
    #endregion The Properties

    4. Read InitParams:
    In the “App.xaml.cs” file, inside the “Application_Startup” event, read the values from InitParams, and assign them to the properties previously defined:

    private void Application_Startup( object sender, StartupEventArgs argTheEventData )
    {
    Page pagTheSilverlightControl;
    IDictionary dicTheParameters ;

    //Obtain parameters:
    dicTheParameters = argTheEventData.InitParams;

    //Create instance:
    pagTheSilverlightControl = new Page();

    //Assign parameters:
    if ( dicTheParameters.ContainsKey( “TheValue1” ) )
    {
    pagTheSilverlightControl.TheValue1 = dicTheParameters[ “TheValue1” ];
    }
    if ( dicTheParameters.ContainsKey( “TheValue2” ) )
    {
    pagTheSilverlightControl.TheValue2 = dicTheParameters[ “TheValue2” ];
    }
    }

    IMPORTANT: Notice that the “Application_Startup” event is in “App.xaml.cs” and not in “Page.xaml.cs” (or however you call your control)

    5. Use values sent
    Inside “Page.xaml.cs” use the values according to your needs. For example:

    lblTheTitle.Content = this.TheValue2;

    To send “special” characters:
    Values being sent through “InitParameters” are not automatically escaped so, if you directly send an “=” or a “,” as a value, it won’t work. You need to “escape” them yourself. For example, to send a connection string, you could do something like this:

    1. Assign parameters:
    In the “Page_Load” for the host page, assign and escape the connection string with something like this:

    slvTest01.InitParameters = String.Format( “cnnNorthwind={0}”, ConfigurationManager.ConnectionStrings[ “cnnNorthwind” ].ConnectionString.Replace( “=”, “&eq;” ) );

    4. Read InitParams:
    In the “App.xaml.cs” file, inside the “Application_Startup” event, read and unescape the values from InitParams:

    private void Application_Startup( object sender, StartupEventArgs argTheEventData )
    {
    Page pagTheSilverlightControl;
    IDictionary dicTheParameters ;

    //Obtain parameters:
    dicTheParameters = argTheEventData.InitParams;

    //Create instance:
    pagTheSilverlightControl = new Page();

    //Assign parameters:
    if ( dicTheParameters.ContainsKey( “cnnNorthwind” ) )
    {
    pagTheSilverlightControl.TheConnectionString = dicTheParameters[ “cnnNorthwind” ].Replace( “&eq;”, “=” );
    }
    }

  2. Cannot implicitly convert type ‘System.Collections.Generic.IDictionary’ to ‘System.Collections.IDictionary’. An explicit conversion exists (are you missing a cast?)

  3. Hi,
    Thank you for your information but
    I want to pass parameter in silverlight in secure way.all of the above it seems don’t secure.
    how can read cookie in silverlight for passing parameter such as userId?

    Thanks

  4. This example has been tested on SilverLight 3. Create a SilverLight control like this:

    The code for the control is as follows:

    namespace PasoParametros01Silver
    {
    public partial class FirstPage : UserControl
    {
    public FirstPage()
    {
    InitializeComponent();
    }

    public IDictionary TheParameters;

    private void ViewParametersCmd_Click( object sender, RoutedEventArgs e )
    {
    DebugTxt.Text = “Number of parameters: ” + this.TheParameters.Count.ToString() + “\r\n”;

    for ( Int32 i = 0; i < this.TheParameters.Count; i++ )
    {
    DebugTxt.Text += this.TheParameters.ElementAt( i ).Key + ” : ” + this.TheParameters.ElementAt( i ).Value + “\r\n”;
    }
    }

    } //public partial class FirstPage : UserControl

    } //namespace PasoParametros01Silver

    Notice the exposed property called “TheParameters”.

    Open the code window for “App.xaml.cs” and modify “Application_Startup” like this:

    private void Application_Startup( object sender, StartupEventArgs TheEventData )
    {
    FirstPage TheFirstPage;

    TheFirstPage = new FirstPage();
    TheFirstPage.TheParameters = TheEventData.InitParams;
    this.RootVisual = TheFirstPage;
    }

    Notice “StartupEventArgs TheEventData”

     
    Open the web page that will host the SilverLight control (Default.Aspx for example) and write the following to use the control:

    Run the web page and click “View Parameters”. You should see three parameters and the corresponding values:

    Parameters:
    Number of parameters: 3
    FirstName : Dilla
    AptNumber : 301
    Registered : true

  5. “Open the web page that will host the SilverLight control (Default.Aspx for example) and write the following to use the control:”

    Where is the explanation ? How do you apass the parameters from the ASPX page ?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s