While coding, there maybe case you want to get some data from server side without a full page postback to gain better user experience and performance), for example, show teaser profile onmouseover, server side validations, etc. By using javascript and webservice, you can do it just like a snap. Below is how it works...
1, Define a script service by adding 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 blnIsUserExists to true if exists.
return blnIsUserExists;
}
}
2, Add a ScriptMananger to the page, and register script service to the ScriptManager...
<asp:ScriptManager runat="server" ID="scriptManagerId">
<Services>
<asp:ServiceReference Path="UserValidationService.asmx" />
</Services>
</asp:ScriptManager>
3, Call webservice just like calling a local javascript function...
<script type="text/javascript">
function validateUserName()
{
var userName = document.getElementById("txtUserName").value;
UserValidationService.ValidateUserName(userName,showValidateResult,validateUserNameError);
}
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>