How To Trigger ASP.NET Function With Javascript

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"

<html xmlns="" >
<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);
  <form id="form1" runat="server">

  <asp:Button ID="Button1" OnClientClick="MyFunction1() ; return false;" runat="server"
Text="Button1" />
  <asp:Button ID="Button2" OnClientClick="MyFunction2() ; return false;" runat="server"
Text="Button2" />

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")
           else if (eventTarget == "MyServerSideFunction2")

   private void Fun1(string arg)

   private void Fun2(string arg)
Next Post Previous Post
No Comment
Add Comment
comment url