Using ASP.NET Ajax's pageLoad() method for Silverlight control creation

The technique usually used for creating the Silverlight control is to call Silverlight.createObject(...) from within a client-side script block just under the <div> element to be used as the host element. This has always bothered me since it felt rather fragile to expose embedded script directly within the form element on a page (for an ASP.NET page anyway).

It occurred to me today that the pageLoad() method of ASP.NET Ajax is really the ideal place to create a Silverlight control for a page, since it is not invoked until the scripts have all been loaded, and the client-side DOM is in place. Here's an example of an ASP.NET Ajax page and the accompanying JavaScript file that loads a Silverlight control using this technique:

Default.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Silverlight</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="_scriptManager" runat="server">
          <Scripts>
            <asp:ScriptReference Path="~/Silverlight.js" />
            <asp:ScriptReference Path="~/Default.aspx.js" />
          </Scripts>
        </asp:ScriptManager>
        <div>
        <h1>Silverlight hosted within an ASP.NET Ajax page</h1>
        
        <div id="slControlHost">
        </div>

        </div>
    </form>
</body>
</html>

Default.aspx.js
function pageLoad(sender, args)
{
  // Called after all scripts have been loaded
  Silverlight.createObject("Default.xaml", $get('slControlHost'), 
                                 "slControl",
                                 {width:'1024', height:'530',
                                 version:'1.0' },
                                 {onError:null, onLoad:null},
                                 null);         
}

Now the page is free from any embedded script, and less susceptible to incidental errors introduced while doing layout - I like it!

Posted Aug 01 2007, 02:33 PM by fritz-onion
Filed under:

Comments

Shawn Wildermuth wrote re: Using ASP.NET Ajax's pageLoad() method for Silverlight control creation
on 08-01-2007 3:42 PM
Nice!
Rick Stoelinga wrote re: Using ASP.NET Ajax's pageLoad() method for Silverlight control creation
on 08-03-2007 1:54 PM
yeah...that has been bugging me as well. I really don't like embedding javascript in the page below the body tag. I ran into a bug with this when trying to combine it on a page that also included an embedded flash object.
anothr user wrote Anothr feed track -Onion Blog
on 09-03-2007 7:11 PM
One new subscriber from Anothr Alerts
Rasheed wrote re: Using ASP.NET Ajax's pageLoad() method for Silverlight control creation
on 10-15-2007 11:19 PM
Ajax control creation

Add a Comment

(required)  
(optional)
(required)  
Remember Me?