Introduction
After posting a small article about how to create a password box in Silverlight 2 beta 2, I have got one request about usage of pure HTML password input instead of TextBox
from Silverlight. I thought that this could be useful to present also how to sent objects from HTML page through JavaScripts into Silverlight page.
Using the Code
To establish communication with Silverlight page, we have to do two easy things.
Mark with special attribute name a method or a whole class that it will be accessed via JavaScript and then register an instance of this class.
Below is a Silverlight page class (generated from the project template) where I added RegisterScriptableObject
line. Here, we tell to our Silverlight control that we would like to show this object with label loginProvider
to JavaScript calls.
Secondly, we have a method which is a part of Page
class with special ScriptableMember
attribute. This means that we will expose this function for JavaScript calls. Summing it up, we published loginProvider
with one available method - Login
.
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("loginProvider", this);
}
[ScriptableMember()]
public void Login(string password, string login)
{
this.Message.Text = "Your login is: " + login +
"\r\nFirst letter of your password is: " +
(password.Length > 0 ? password[0].ToString() : "");
}
}
The second thing is to create an HTML code which will be responsible for collecting data from the entry form and send it to Silverlight control. For this purpose, we have created invokeManagedCode
method which will be launched after pressing Login button. What could be not clear is where the sl2b2
tag is from. For this purpose, I have added an additional attribute to object instance of Silverlight control (inside the div
tag).
<script type="text/javascript">
function invokeManagedCode(){
var form = document.getElementById("loginpanel");
var password = form.password.value;
var user = form.user.value;
var control = document.getElementById("sl2b2");
control.Content.loginProvider.Login(password,user);
}
</script>
</head>
<body>
<form id="loginpanel" name="input" ACTION="javascript:invokeManagedCode()">
Username:
<input type="text" name="user">
Password:
<input type="password" name="password">
<input type="Submit" value="Login" >
Points of Interest
For sure, communication between HTML content and Siliverlight can be done in several ways. This is only one of them.
History
- 1st July, 2008: Initial post