Sunday, 30 September 2012

Java script Interaction with server in ASP.NET

java script is a alanguage which runs on client machine
but we can interact with server in asp.net
Server returns data and it catch by java script functions and rebder
data as you have hanldle it.Its prevent full page paost back..My example will show
random number in textbox generated by server.

.aspx page code..
 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Communication With Server</title>
    <script language="javascript">
        function GetNumber()
        {
            UseCallback();
        }
        function GetRandomNumberFromServer(TextBox1,context)
        {
            document.forms[0].TextBox1.value=TextBox1;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br /><br />
        <input type="button" value="Get Random Number.." onclick="GetNumber()" />
    </div>
    </form>
</body>
</html>

Server Side Code..

public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
    private string _callbackResult = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        string cbreference = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetRandomNumberFromServer", "context");
        string cbscript = "function UseCallback(arg,context){" + cbreference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbscript, true);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    public void RaiseCallbackEvent(string eventArg)
    {
        Random rnd = new Random();
        _callbackResult = rnd.Next().ToString();
    }
    public string GetCallbackResult()
    {
        return _callbackResult;
    }
}