elitechen 2010-01-04
Silverligh的应用范围比较广泛。在开发人员实际使用中,可以轻松的实现各种基于多媒体方面功能。基于安全原因的考虑,Silverlight是不允许直接访问数据库的。但还是有很多方法来间接实现Silverlight对数据库的访问。
比如以下的三种方式:1 RESTful API;2 在Silverlight下借助JavaScript来实现访问数据库;3 利用.NET Web服务模板——Silverlight-enabled。本文将主要介绍一下后俩种方法。
利用JavaScript实现Silverlight与数据库的交互
只要在Silverlight事件处理的后面添加调用以下简单的JavaScript代码即可。其中”callWebService”是JavaScript的函数。
关于JavaScript的调用可以参照一下内容:
通过ScriptServiceAttribute添加
[ScriptService]
public class UserValidationService:
System.Web.Services.WebService
{
[WebMethod]
public bool ValidateUserName
(string strInput)
{
return !GetUserByUserName(strInput);
//If user exists return false
indicates the name is no longer availabe.
}
private bool GetUserByUserName
(string strUserName)
{
bool blnIsUserExists = false;
//Call database API to see if the
username is availabe, set blnIsUser
Exists to true if exists.
return blnIsUserExists;
}
} 通过页面添加ScriptMananger控件
< asp:ScriptManager runat="server" ID="scriptManagerId"> < Services> < asp:ServiceReference Path= "UserValidationService.asmx" /> < /Services> < /asp:ScriptManager>
像调用JavaScript局部函数一样调用Webservice
< script type="text/javascript">
function validateUserName()
{
var userName = document.getElementById
("txtUserName").value;
UserValidationService.ValidateUserName
(userName,showValidateResult,validate
UserNameError);
}
function validateUserNameError(result)
{
//Do nothing if any error, ideally,
we should log this error to database.
}
function showValidateResult(result)
{
//Since it is only a boolean value,
no need to get result.d, if result
contains .net object,
// use result.length and result.d
to retrieve the object.
if(!result)
{
//Not available
}else
{
//Username is still available
}
}
< /script> 利用Silverlight-enabled Webservice实现Silverlight与数据库的交互