Silverlight 2.0: Passing empty strings from JavaScript to .NET is not possible

.NET, Silverlight, Technical stuff
See comments

Update: Check this post

Apparently, it is not possible to pass empty strings from JavaScript to .NET. Even worse, if the .NET method has two string parameters, and one of them only is an empty string, the .NET method will not be called.

This is fairly easy to demonstrate:

  • Create a new Silverlight 2.0 application in Visual Studio 2008
  • Open the file “Page.xaml”
  • Add two TextBlocks:
<TextBlock x:Name="DisplayTextBlock1"
<TextBlock x:Name="DisplayTextBlock2"

  • Open the file “Page.xaml.cs”
  • Modify the class as follows:
public partial class Page : Canvas
  public void Page_Loaded(object o, EventArgs e)
    // Required to initialize variables
    WebApplication.Current.RegisterScriptableObject("Page", this);

  public void Go(string message1, string message2)
    DisplayTextBlock1.Text = message1;
    DisplayTextBlock2.Text = message2;

  • Open the file “TestPage.html”.
  • Add a CSS class to the header:
  position: absolute;
  top: 50px;
  left: 50px;
  background-color: Green;
  padding: 10px;

  • Add a DIV under the “SilverlightControlHost” DIV
<div id="HtmlForm">
  <form action="TestPage.html">
    <input type="text" id="InputTextBox1" />
    <input type="text" id="InputTextBox2" />
    <br />
    <input type="button" value="Go" onclick="callDotNet();" />

  • Open “TestPage.html.js”
  • Modify the code as follows:
var silverlightControl= null;

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
    source: "Page.xaml",
    parentElement: document.getElementById("SilverlightControlHost"),
    id: "SilverlightControl",
    properties: {
      width: "100%",
      height: "100%",
      version: "1.1",
      enableHtmlAccess: "true",
      background: "#00FFFFFF",
      isWindowless: "True"
    events: {
      onLoad: function(control, userContext, rootElement)
        silverlightControl = control;

function callDotNet()

  • Run the code

If you enter any string into the first and the second textfields, and press the “Go” button, the Silverlight TextBlocks will be updated. If however one or both of the textfields contain an empty string, the .NET method is not even invoked.

This is annoying, because it forces the Silverlight developers to add a check in JavaScript, and make sure that the strings are not empty. Error handling is much easier if you can do everything in .NET, first because it’s cleaner, then because localizing error messages in JavaScript is a hassle. It would be great if the .NET method was called even if a parameter is an empty string.

A repro is posted on my site.

Previous entry | Next blog entry

Comments for Silverlight 2.0: Passing empty strings from JavaScript to .NET is not possible