Working with Page Methods in ASP.net


Here is our .aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Working with ASP.Net Page Methods is really awesome</title>

    <script type="text/javascript">

        function GetCurrentDate() {

            PageMethods.GetCurrentDate(onDateSuccess, onDateError);
        }

        function onDateSuccess(result) {
            alert('Today is ' + result);
        }

        function onDateError(result) {
            alert('error occured');
        }

    </script>

    <script type="text/javascript">

        function GetResult(empCode) {
            PageMethods.GetResult(empCode, onsuccess, onerror);
        }

        function onsuccess(result) {
            alert('Welcome, '+ result);
        }

        function onerror(result) {
            alert('error occured');
        }

    </script>
</head>
<body>
    <form id="frmPageMethod" runat="server">
    <asp:ScriptManager ID="scmResult" runat="server" EnablePageMethods="true"></asp:ScriptManager>
    <div>
    <asp:Button ID="btnGetCurrentDate" runat="server" Text="Current Date" OnClientClick="GetCurrentDate(); return false;" />
    <asp:TextBox ID="txtempCode" runat="server"></asp:TextBox> <asp:Button ID="btnClick" runat="server" OnClientClick="GetResult(txtempCode.value); return false;" Text="Get Result" />
    </div>
    </form>
</body>
</html>

Here is our .aspx.cs code:
[WebMethod]
    public static string GetCurrentDate()
    {
        string date = System.DateTime.Now.ToString("MM/dd/yyyy");
        return date;
    }

    [WebMethod]
    public static string GetResult(string empCode)
    {
        SqlConnection dbconn;
        SqlCommand dbcomm;
        SqlDataReader dreader;
        string sqlQuery;
        string empName = string.Empty;

        dbconn = new SqlConnection("Data Source=localhost;Initial Catalog=myDB;Integrated Security=True");
        dbconn.Open();
        sqlQuery = "SELECT TOP 1 EmpID, Sal, (FName+' '+LName) Name, ECode  FROM empTable WHERE ECode = '" + empCode + "' ";
        dbcomm = new SqlCommand(sqlQuery, dbconn);
        dreader = dbcomm.ExecuteReader();
        while (dreader.Read())
        {
            empName = dreader["Sal"].ToString() + " " + dreader["Name"].ToString();
        }
        dreader.Close();
        dbconn.Close();
        return empName;
    }

Points to Remember:
·         We must set ScriptManaget EnablePageMethods property to true
·         We must write our function after declararing name space System.Web.Services and [WebMethod] before function
·         Access the WebMethods in jacascript function like PageMethods.YourFunction i.e. PageMethods.GetCurrentDate(onsuccess, onerror)
·         Write your javascript function on .aspx page and call it on click event of button


I hope you enjoy the topic.
Cheers

Comments