Pass Values from ASP.NET to Silverlight Control

Posted by: Suprotim Agarwal , on 7/7/2008, in Category Silverlight 2, 3, 4 and 5
Views: 60609
Abstract: In one of the previous articles, we have seen how Silverlight can be hosted with ASP.NET. We also saw how you can Navigate and Pass Values between Silverlight Pages. One of the thoughts that now tickle my brain is how can we enable communication between ASP.NET and Silverlight. Well there are a couple of options and we will discuss one of them in this article.
Pass Values from ASP.NET to Silverlight Control
 
In one of the previous articles, we have seen how Silverlight can be hosted with ASP.NET. We also saw how you can Navigate and Pass Values between Silverlight Pages. One of the thoughts that now tickle my brain is how can we enable communication between ASP.NET and Silverlight. Well there are a couple of options and we will discuss one of them in this article.
To pass values from ASP.NET page to Silverlight, you can use either a query string or cookies. The Silverlight code can then make use of the classes in the System.Windows.Browser namespace to access this information. In this article, we will use the query string technique to pass the FirstName and LastName from one ASP.NET page to another ASP.NET page that contains the Silverlight control and access and display the values in a TextBlock.
I am assuming that you know how to create a Silverlight web application. If you are unfamiliar with hosting Silverlight content in ASP.NET, check my article ‘Hosting Silverlight Content in ASP.NET 3.5’ before proceeding ahead.
Step 1: Open Visual Studio 2008 > File > New Project > Select the language (C# or VB) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Application’.
Step 2: Type a name (SilverlightToASP.NETParameter) and location for the project and click ok. Choose the first option ‘Add a new Web to the solution for hosting the control’ and the project type as Web Site and click OK. You will see that two projects are created: SilverlightToASP.NETParameterWeb and SilverlightToASP.NETParameter.
Step 3: In the Default.aspx kept in the ‘SilverlightToASP.NETParameterWeb’ project, add two textboxes and a button.
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnGo" runat="server" onclick="btnGo_Click" Text="Go" />
   
    </div>
    </form>
In the code-behind, add the following code to pass the values from Default.aspx to SilverlightToASP.NETParameterTestPage.aspx:
C#
    protected void btnGo_Click(object sender, EventArgs e)
    {
        if (txtFName.Text != String.Empty && txtLName.Text != String.Empty)
        {           
            Response.Redirect("~/SilverlightToASP.NETParameterTestPage.aspx?FName=" + txtFName.Text.Trim() + "&LName=" + txtLName.Text.Trim());
        }
    }
VB.NET
      Protected Sub btnGo_Click(ByVal sender As Object, ByVal e As EventArgs)
            If txtFName.Text <> String.Empty AndAlso txtLName.Text <> String.Empty Then
                  Response.Redirect("~/SilverlightToASP.NETParameterTestPage.aspx?FName=" & txtFName.Text.Trim() & "&LName=" & txtLName.Text.Trim())
            End If
      End Sub
Step 4: As you might have guessed, the SilverlightToASP.NETParameterTestPage.aspx contains the Silverlight control that lets you embed XAML content in an asp.net page.
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div style="height:100%;">
            <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightToASP.NETParameter.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />
        </div>
    </form>
We will now modify the XAML content. So move to the Page.xaml kept in the ‘SilverlightToASP.NETParameter’ project and add a TextBlock to it
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="txtName" Width="400"></TextBlock>
    </Grid>
Step 5: In the Page.xaml.cs or Page.xaml.vb, add the following code
C#
    public partial class Page : UserControl
    {
        string fName = String.Empty;
        string lName = String.Empty;
 
        public Page()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Page_Loaded);          
        }
 
        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            IDictionary<string, string> qString = HtmlPage.Document.QueryString;
            foreach (KeyValuePair<string, string> kvp in qString)
            {
                string k = kvp.Key;
                string v = kvp.Value;
                if (k == "FName")
                    fName = v;
                else if (k == "LName")
                    lName = v;
            }
 
            txtName.Text = "Welcome, " + fName + " " + lName;
        }
    }
VB.NET
      Public Partial Class Page
            Inherits UserControl
            Private fName As String = String.Empty
            Private lName As String = String.Empty
 
            Public Sub New()
                  InitializeComponent()
                  AddHandler Loaded, AddressOf Page_Loaded
            End Sub
 
            Private Sub Page_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  Dim qString As IDictionary(Of String, String) = HtmlPage.Document.QueryString
                  For Each kvp As KeyValuePair(Of String, String) In qString
                        Dim k As String = kvp.Key
                        Dim v As String = kvp.Value
                        If k = "FName" Then
                              fName = v
                        ElseIf k = "LName" Then
                              lName = v
                        End If
                  Next kvp
 
                  txtName.Text = "Welcome, " & fName & " " & lName
            End Sub
      End Class
In the code above, we are using the HtmlPage.Document class to access and manipulate the browser’s DOM. The HTMLDocument.QueryString returns a collection of name/value pairs that represent the query string parameters on the page's URL. We access these parameters and store them in a IDictionary<string,string>. We then use foreach to enumerate dictionary elements which are retrieved as KeyValuePair objects. The value is then assigned to two local variables, fName and lName.
Note: This was a crude way of doing it to keep things simple and to the point. You can also use get set properties to access the name.
Now right click Default.aspx and ‘Set as Start Page’. Run the application. Enter the firstname and lastname in the textbox and click the button ‘Go’. You will observe that you have passed parameters from asp.net to the TextBlock kept in the Silverlight control.
Now if you want to try the vice-versa, i.e. pass values from the Silverlight page to the ASP.NET page, the easiest way I have come across is to call an ASP.NET web service from the Silverlight application and then pass in the values. Well that's it for the timebeing. I hope this article was useful and I thank you for viewing it.
To view other Silverlight articles written by me, check the link over here.
If you liked the article,  Subscribe to my RSS Feed. 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by shashank on Wednesday, July 23, 2008 7:22 AM
gives an error at                                        IDictionary<string, string> qString = "HtmlPage.Document.QueryString";
Comment posted by Samuel on Sunday, November 9, 2008 11:21 PM
I like this article since it also uses VB source code.
Comment posted by Prasad K on Friday, June 26, 2009 11:13 AM
Very Good artical , It save my time . Thank you very much for providing this idea !
Comment posted by Anil Kumar Pandey on Tuesday, September 14, 2010 7:36 AM
Very Nice article hope to see some more.....
Comment posted by Ganesan on Monday, September 27, 2010 11:07 AM
Very useful artilcle  and it save my time
Comment posted by ram on Wednesday, December 8, 2010 7:34 AM
thanks for the article.

f you would write code also on how to pass using cookies that makes the article more complete.
Comment posted by Hamdy Flash on Sunday, May 22, 2011 12:49 AM
Thanks alot vey useful
Comment posted by Vema Reddy on Friday, August 3, 2012 12:41 AM
Thanks...Nice article
It was helpful to me..
Comment posted by Sunaina on Saturday, January 24, 2015 3:40 PM
I tried it but it gives error as

HtmlPage does not exist in current context