基于安全原因的考虑,Silverlight是不允许直接访问数据库的。但还是有很多方法来间接实现Silverlight对数据库的访问。比如以下的三种方式:1 RESTful API;2 在Silverlight下借助JavaScript来实现访问数据库;3 利用.NET Web服务模板——Silverlight-enabled。本文将主要介绍一下后俩种方法。
利用JavaScript实现Silverlight与数据库的交互
只要在Silverlight事件处理的后面添加调用以下简单的JavaScript代码即可。其中”callWebService”是JavaScript的函数。
2 {
3 System.Windows.Browser.HtmlPage.Window.Invoke( " callWebService " , null );
4 }
关于JavaScript的调用可以参照一下内容:
通过ScriptServiceAttribute添加
2 public class UserValidationService: System.Web.Services.WebService
3 {
4 [WebMethod]
5 public bool ValidateUserName( string strInput)
6 {
7 return ! GetUserByUserName(strInput); // If user exists return false indicates the name is no longer availabe.
8 }
9
10 private bool GetUserByUserName( string strUserName)
11 {
12 bool blnIsUserExists = false ;
13 // Call database API to see if the username is availabe, set blnIsUserExists to true if exists.
14 return blnIsUserExists;
15 }
16 }
通过页面添加ScriptMananger控件
2 < Services >
3 < asp:ServiceReference Path = " UserValidationService.asmx " />
4 </ Services >
5 </ asp:ScriptManager >
像调用JavaScript局部函数一样调用Webservice
2 function validateUserName()
3 {
4 var userName = document.getElementById( " txtUserName " ).value;
5 UserValidationService.ValidateUserName(userName,showValidateResult,validateUserNameError);
6
7 }
8 function validateUserNameError(result)
9 {
10 // Do nothing if any error, ideally, we should log this error to database.
11 }
12
13 function showValidateResult(result)
14 {
15 // Since it is only a boolean value, no need to get result.d, if result contains .net object,
16 // use result.length and result.d to retrieve the object.
17 if ( ! result)
18 {
19 // Not available
20 } else
21 {
22 // Username is still available
23 }
24 }
25 </ script >
利用Silverlight-enabled Webservice实现Silverlight与数据库的交互
首先通过模板创建一个Silverlight-enabled Webservice,然后将数据库和其他Server-related添加到服务里。接下来,将此服务添加引用到Silverlight 应用中。最后利用如下代码从Silverlight 应用中调用webservice。
2 ......
3 .....
4
5 private void btnSend_Click( object sender, RoutedEventArgs e)
6 {
7 if ( ! String.IsNullOrEmpty(txtMessage.Text.Trim()))
8 {
9 lstHisotryMessage.Items.Add( " Gene: " + txtMessage.Text.Trim());
10 GeneMessage message = new GeneMessage();
11 message.Body = txtMessage.Text.Trim();
12 MyServiceclient = new MyService();
13 client.SendMessageCompleted += new EventHandler < SendMessageCompletedEventArgs > (client_SendMessageCompleted);
14 client.SendMessageAsync(message);
15 }
16 else
17 {
18 MessageBox.Show( " You cannot send empty message! " );
19 }
20 }
21
22 protected void client_SendMessageCompleted( object sender, SendMessageCompletedEventArgs e)
23 {
24 txtMessage.Text = e.Result.MessageID.ToString();
25 }
本文链接: http://tech.it168.com/a2009/1105/804/000000804641.shtml