In this article, I will show you how to trigger ASP.NET server-side function from JavaScript.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Trigger.aspx.cs"
Inherits="Trigger" %>
<!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>Untitled Page</title>
<script type="text/javascript">
function MyFunction1()
{
var valueToSetTo = 'abc'
__doPostBack('MyServerSideFunction1', valueToSetTo);
}
function MyFunction2()
{
var valueToSetTo = 'xyz'
__doPostBack('MyServerSideFunction2', valueToSetTo);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" OnClientClick="MyFunction1() ; return false;" runat="server"
Text="Button1" />
<asp:Button ID="Button2" OnClientClick="MyFunction2() ; return false;" runat="server"
Text="Button2" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Trigger : System.Web.UI.Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
//Insure that the __doPostBack() JavaScript method is created...
this.ClientScript.GetPostBackEventReference(this, string.Empty);
if (this.Page.IsPostBack)
{
string eventTarget =
(this.Request["__EVENTTARGET"] == null ? string.Empty : this.Request["__EVENTTARGET"]);
string eventArgument =
(this.Request["__EVENTARGUMENT"] == null ? string.Empty : this.Request["__EVENTARGUMENT"]);
if (eventTarget == "MyServerSideFunction1")
{
Fun1(eventArgument);
}
else if (eventTarget == "MyServerSideFunction2")
{
Fun2(eventArgument);
}
}
}
private void Fun1(string arg)
{
Response.Write(arg);
}
private void Fun2(string arg)
{
Response.Write(arg);
}
}