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.
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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