Calling server side method by using Java Script.
We can call the server side function in several ways. Here we will discuss on calling web method by using Page method object on java script. From below example, I am calling the server side method when user closes the ASP.NET web application window.
Steps to call the server side method by using Java Script.
1) Open Visual studio and select Web Service from VB.Net templates.
2) Create one Web Method by using your own implementation.
3) Drag the AJAX Script Manger and set the property "EnablePageMethods="true"";
4) Call the server side method by using Page Method object. Ex. PageMethods.deleteMethod(14);
HTML Part:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication5._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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
<script type="text/javascript">
window.onbeforeunload = function(e)
{
try {
e = e || window.event;
PageMethods.deleteMethod(14);
alert("Window is closing...");
}
catch (ex)
{
alert(ex.message);
}
}
</script>
</body>
</html>
Code Behind Code in VB.NET:
Imports System.Data.OleDb
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Shared Function deleteMethod(ByVal custid As String) As String
Dim conn As OleDbConnection = Nothing
Dim connection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
conn = New OleDbConnection(connection)
Dim cmd As New Data.OleDb.OleDbCommand("Delete From table1", conn)
cmd.ExecuteNonQuery()
Dim da As New Data.OleDb.OleDbDataAdapter(cmd)
Dim ds As New Data.DataSet("table1")
Try
da.Fill(ds, "table1")
Catch ex As Exception
Dim ans As String
ans = MsgBox(ex.ToString)
End Try
Return String.Empty
End Function
End Class