<p>I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.</p>

<p>Is it possible to call a method I created in ASP with JavaScript's click event?</p>

[{'answer_id': 3726, 'author': 'brendan', 'author_id': 225, 'author_profile': 'https://Stackoverflow.com/users/225', 'pm_score': 4, 'selected': False, 'text': '<p>You can do it asynchronously using .NET Ajax PageMethods. See <a href="http://web.archive.org/web/20170818234231/http://www.singingeels.com:80/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx" rel="nofollow noreferrer">here</a> or <a href="http://weblogs.asp.net/sohailsayed/archive/2008/02/23/calling-methods-in-a-codebehind-function-pagemethods-from-client-side-using-ajax-net.aspx" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 3752, 'author': 'EndangeredMassa', 'author_id': 106, 'author_profile': 'https://Stackoverflow.com/users/106', 'pm_score': 4, 'selected': False, 'text': '<p>The <a href="http://www.asp.net/ajax/" rel="noreferrer">Microsoft AJAX library</a> will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.</p>\n\n<p>I suggest the Microsoft AJAX library. Once installed and referenced, you just add a line in your page load or init:</p>\n\n<pre><code>Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))\n</code></pre>\n\n<p>Then you can do things like:</p>\n\n<pre><code>&lt;Ajax.AjaxMethod()&gt; _\nPublic Function Get5() AS Integer\n    Return 5\nEnd Function\n</code></pre>\n\n<p>Then, you can call it on your page as:</p>\n\n<pre><code>PageClassName.Get5(javascriptCallbackFunction);\n</code></pre>\n\n<p>The last parameter of your function call must be the javascript callback function that will be executed when the AJAX request is returned.</p>\n'}, {'answer_id': 3777, 'author': 'Adhip Gupta', 'author_id': 384, 'author_profile': 'https://Stackoverflow.com/users/384', 'pm_score': 8, 'selected': True, 'text': "<p>Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):</p>\n\n<p><em>It is a little tricky though... :)</em></p>\n\n<p>i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like</p>\n\n<pre><code>public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}\n</code></pre>\n\n<p>ii. This should add (using <kbd>Tab</kbd>-<kbd>Tab</kbd>) this function to your code file:</p>\n\n<pre><code>public void RaisePostBackEvent(string eventArgument) { }\n</code></pre>\n\n<p>iii. In your onclick event in JavaScript, write the following code:</p>\n\n<pre><code>var pageId = '&lt;%=  Page.ClientID %&gt;';\n__doPostBack(pageId, argumentString);\n</code></pre>\n\n<p>This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.</p>\n\n<p>P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!</p>\n"}, {'answer_id': 8045, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 1, 'selected': False, 'text': "<p>You might want to create a web service for your common methods.<br>\nJust add a WebMethodAttribute over the functions you want to call, and that's about it.<br>\nHaving a web service with all your common stuff also makes the system easier to maintain.</p>\n"}, {'answer_id': 8096, 'author': 'mbillard', 'author_id': 810, 'author_profile': 'https://Stackoverflow.com/users/810', 'pm_score': 6, 'selected': False, 'text': '<p>The <code>__doPostBack()</code> method works well.</p>\n\n<p>Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.</p>\n\n<pre><code>&lt;div style="display: none;"&gt;\n   &lt;asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>From your JavaScript, retrieve the reference to the button using its <em>ClientID</em> and then call the <em>.click()</em> method on it.</p>\n\n<pre><code>var button = document.getElementById(/* button client id */);\n\nbutton.click();\n</code></pre>\n'}, {'answer_id': 26453, 'author': 'David Basarab', 'author_id': 2469, 'author_profile': 'https://Stackoverflow.com/users/2469', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.</p>\n</blockquote>\n\n<p>This is the library called AjaxPro which was written an MVP named <a href="http://weblogs.asp.net/mschwarz/about.aspx" rel="nofollow noreferrer">Michael Schwarz</a>. This was library was not written by Microsoft.</p>\n\n<p>I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.</p>\n'}, {'answer_id': 2802366, 'author': 'Ananda', 'author_id': 328911, 'author_profile': 'https://Stackoverflow.com/users/328911', 'pm_score': -1, 'selected': False, 'text': '<p>This reply works like a breeze for me thanks cross browser:</p>\n\n<blockquote>\n  <p>The __doPostBack() method works well.</p>\n</blockquote>\n\n<p>Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.</p>\n\n<pre><code>&lt;div style="display: none;"&gt; \n    &lt;asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" /&gt; \n&lt;/div&gt; \n</code></pre>\n\n<p>From your JavaScript, retrieve the reference to the button using its ClientID and then call the .Click() method on it:</p>\n\n<pre><code>var button = document.getElementByID(/* button client id */); \n\nbutton.Click(); \n</code></pre>\n\n<blockquote>\n  <p>Blockquote</p>\n</blockquote>\n'}, {'answer_id': 3577148, 'author': 'Ricardo stands with Ukraine', 'author_id': 364568, 'author_profile': 'https://Stackoverflow.com/users/364568', 'pm_score': 1, 'selected': False, 'text': '<p>If the __doPostBack function is not generated on the page you need to insert a control to force it like this:</p>\n\n<pre><code>&lt;asp:Button ID="btnJavascript" runat="server" UseSubmitBehavior="false" /&gt;\n</code></pre>\n'}, {'answer_id': 4977299, 'author': 'David', 'author_id': 365789, 'author_profile': 'https://Stackoverflow.com/users/365789', 'pm_score': 0, 'selected': False, 'text': '<p>Add this line to page load if you are getting object expected error.</p>\n\n<pre><code>ClientScript.GetPostBackEventReference(this, "");\n</code></pre>\n'}, {'answer_id': 6354219, 'author': 'kakani santosh', 'author_id': 799094, 'author_profile': 'https://Stackoverflow.com/users/799094', 'pm_score': 0, 'selected': False, 'text': '<p>You can use <code>PageMethods.Your C# method Name</code> in order to access C# methods or VB.NET methods into JavaScript.</p>\n'}, {'answer_id': 7040311, 'author': 'Behnam Esmaili', 'author_id': 891794, 'author_profile': 'https://Stackoverflow.com/users/891794', 'pm_score': 2, 'selected': False, 'text': '<p>It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button\'s click event.</p>\n\n<p>For triggering an event handler of a control:\nIf you added a ScriptManager on your page already then skip step 1.</p>\n\n<ol>\n<li><p>Add the following in your page client script section</p>\n\n<pre><code>//&lt;![CDATA[\nvar theForm = document.forms[\'form1\'];\nif (!theForm) {\n    theForm = document.form1;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n        theForm.__EVENTTARGET.value = eventTarget;\n        theForm.__EVENTARGUMENT.value = eventArgument;\n        theForm.submit();\n    }\n}\n//]]&gt;\n</code></pre>\n\n<ol start="2">\n<li><p>Write you server side event handler for your control</p>\n\n<p>protected void btnSayHello_Click(object sender, EventArgs e)\n{\n     Label1.Text = "Hello World...";\n}</p></li>\n<li><p>Add a client function to call the server side event handler</p>\n\n<p>function SayHello() {\n        __doPostBack("btnSayHello", "");\n}</p></li>\n</ol></li>\n</ol>\n\n<p>Replace the "btnSayHello" in code above with your control\'s client id.</p>\n\n<p>By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.</p>\n\n<p>One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.</p>\n'}, {'answer_id': 11013093, 'author': 'Despertar', 'author_id': 1160036, 'author_profile': 'https://Stackoverflow.com/users/1160036', 'pm_score': 2, 'selected': False, 'text': '<p>Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.</p>\n\n<p>You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don\'t try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as <a href="http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework" rel="nofollow noreferrer">MVC</a>), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.</p>\n\n<p>My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn\'t see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.</p>\n\n<p><strong>Client-Side:</strong></p>\n\n<pre><code>&lt;script type="text/javascript"&gt;\nvar xmlhttp = new XMLHttpRequest(); // Create object that will make the request\nxmlhttp.open("GET", "http://example.org/api/service", "true"); // configure object (method, URL, async)\nxmlhttp.send(); // Send request\n\nxmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to &lt;p&gt;\n    if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.statsCode == 200) {\n          document.getElementById("resultText").innerHTML = xmlhttp.responseText;\n    }\n};\n&lt;/script&gt;\n</code></pre>\n\n<p>That\'s it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).</p>\n\n<p>The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a <a href="http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_services" rel="nofollow noreferrer">RESTful</a> API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.</p>\n\n<p><strong>Server-Side:</strong></p>\n\n<pre><code>public class DataController : ApiController\n{\n    public HttpResponseMessage&lt;string[]&gt; Get()\n    {\n        HttpResponseMessage&lt;string[]&gt; response = new HttpResponseMessage&lt;string[]&gt;(\n            Repository.Get(true),\n            new MediaTypeHeaderValue("application/json")\n        );\n\n        return response;\n    }\n}\n</code></pre>\n\n<p><strong>Global.asax</strong></p>\n\n<p>Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.</p>\n\n<pre><code>void Application_Start(object sender, EventArgs e)\n{\n    RouteTable.Routes.MapHttpRoute("Service", "api/{controller}/{id}");\n}\n</code></pre>\n\n<p>With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.</p>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href="http://www.w3schools.com/ajax/default.asp" rel="nofollow noreferrer">Ajax</a>,</li>\n<li><a href="http://www.w3schools.com/jquery/jquery_ajax.asp" rel="nofollow noreferrer">jQuery Ajax</a>,</li>\n<li><a href="http://www.asp.net/web-api/overview/hosting-aspnet-web-api/using-web-api-with-aspnet-web-forms" rel="nofollow noreferrer">Controller in Webforms</a></li>\n</ul>\n'}, {'answer_id': 15403629, 'author': 'Robin', 'author_id': 2042366, 'author_profile': 'https://Stackoverflow.com/users/2042366', 'pm_score': 0, 'selected': False, 'text': '<p>Try this:</p>\n\n<pre><code>if(!ClientScript.IsStartupScriptRegistered("window"))\n{\n    Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "pop();", true);\n}\n</code></pre>\n\n<p>Or this</p>\n\n<pre><code>Response.Write("&lt;script&gt;alert(\'Hello World\');&lt;/script&gt;");\n</code></pre>\n\n<p>Use the OnClientClick property of the button to call JavaScript functions...</p>\n'}, {'answer_id': 19113786, 'author': 'The Hungry Dictator', 'author_id': 2763709, 'author_profile': 'https://Stackoverflow.com/users/2763709', 'pm_score': 0, 'selected': False, 'text': "<p>You can also get it by just adding this line in your JavaScript code:</p>\n\n<pre><code>document.getElementById('&lt;%=btnName.ClientID%&gt;').click()\n</code></pre>\n\n<p>I think this one is very much easy!</p>\n"}, {'answer_id': 19939808, 'author': 'davrob01', 'author_id': 1839956, 'author_profile': 'https://Stackoverflow.com/users/1839956', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>I'm trying to implement this but it's not working right. The page is\n  posting back, but my code isn't getting executed. When i debug the\n  page, the RaisePostBackEvent never gets fired. One thing i did\n  differently is I'm doing this in a user control instead of an aspx\n  page.</p>\n</blockquote>\n\n<p>If anyone else is like Merk, and having trouble over coming this, I have a solution:</p>\n\n<p>When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:</p>\n\n<pre><code>public void RaisePostBackEvent(string _arg)\n{\n    UserControlID.RaisePostBackEvent(_arg);\n}\n</code></pre>\n\n<p>Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.</p>\n\n<p>Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):</p>\n\n<pre><code>public void RaisePostBackEvent(string _arg)\n{\n    UserControlID.method1();\n    UserControlID.method2();\n}\n</code></pre>\n"}, {'answer_id': 23781882, 'author': 'SRV', 'author_id': 3660574, 'author_profile': 'https://Stackoverflow.com/users/3660574', 'pm_score': 3, 'selected': False, 'text': '<p>I think blog post <em><a href="http://www.dotnetawesome.com/2013/12/how-to-fetch-show-sql-server-database-data-using-ajax-jquey.html" rel="nofollow noreferrer">How to fetch &amp; show SQL Server database data in ASP.NET page using Ajax (jQuery)</a></em> will help you.</p>\n\n<p><strong>JavaScript Code</strong></p>\n\n<pre><code>&lt;script src="http://code.jquery.com/jquery-3.3.1.js" /&gt;\n&lt;script language="javascript" type="text/javascript"&gt;\n\n    function GetCompanies() {\n        $("#UpdatePanel").html("&lt;div style=\'text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px\'&gt;Please Wait...&lt;/div&gt;");\n        $.ajax({\n            type: "POST",\n            url: "Default.aspx/GetCompanies",\n            data: "{}",\n            dataType: "json",\n            contentType: "application/json; charset=utf-8",\n            success: OnSuccess,\n            error: OnError\n        });\n    }\n\n    function OnSuccess(data) {\n        var TableContent = "&lt;table border=\'0\'&gt;" +\n                                "&lt;tr&gt;" +\n                                    "&lt;td&gt;Rank&lt;/td&gt;" +\n                                    "&lt;td&gt;Company Name&lt;/td&gt;" +\n                                    "&lt;td&gt;Revenue&lt;/td&gt;" +\n                                    "&lt;td&gt;Industry&lt;/td&gt;" +\n                                "&lt;/tr&gt;";\n        for (var i = 0; i &lt; data.d.length; i++) {\n            TableContent += "&lt;tr&gt;" +\n                                    "&lt;td&gt;"+ data.d[i].Rank +"&lt;/td&gt;" +\n                                    "&lt;td&gt;"+data.d[i].CompanyName+"&lt;/td&gt;" +\n                                    "&lt;td&gt;"+data.d[i].Revenue+"&lt;/td&gt;" +\n                                    "&lt;td&gt;"+data.d[i].Industry+"&lt;/td&gt;" +\n                                "&lt;/tr&gt;";\n        }\n        TableContent += "&lt;/table&gt;";\n\n        $("#UpdatePanel").html(TableContent);\n    }\n\n    function OnError(data) {\n\n    }\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>ASP.NET Server Side Function</strong></p>\n\n<pre><code>[WebMethod]\n[ScriptMethod(ResponseFormat= ResponseFormat.Json)]\npublic static List&lt;TopCompany&gt; GetCompanies()\n{\n    System.Threading.Thread.Sleep(5000);\n    List&lt;TopCompany&gt; allCompany = new List&lt;TopCompany&gt;();\n    using (MyDatabaseEntities dc = new MyDatabaseEntities())\n    {\n        allCompany = dc.TopCompanies.ToList();\n    }\n    return allCompany;\n}\n</code></pre>\n'}, {'answer_id': 27164392, 'author': 'KDJ', 'author_id': 3889892, 'author_profile': 'https://Stackoverflow.com/users/3889892', 'pm_score': 1, 'selected': False, 'text': "<p>Regarding:</p>\n\n<pre><code>var button = document.getElementById(/* Button client id */);\n\nbutton.click();\n</code></pre>\n\n<p>It should be like:</p>\n\n<pre><code>var button = document.getElementById('&lt;%=formID.ClientID%&gt;');\n</code></pre>\n\n<p>Where formID is the ASP.NET control ID in the .aspx file.</p>\n"}, {'answer_id': 35812420, 'author': 'Sumit Kumar', 'author_id': 6021773, 'author_profile': 'https://Stackoverflow.com/users/6021773', 'pm_score': 0, 'selected': False, 'text': '<p>Please try this:</p>\n\n<pre><code>&lt;%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %&gt;;\n</code></pre>\n\n<p>ddlVoucherType is a control which the selected index change will call... And you can put any function on the selected index change of this control.</p>\n'}, {'answer_id': 40970986, 'author': '6134548', 'author_id': 6134548, 'author_profile': 'https://Stackoverflow.com/users/6134548', 'pm_score': 0, 'selected': False, 'text': "<p>The simplest and best way to achieve this is to use the <code>onmouseup()</code> JavaScript event rather than <code>onclick()</code></p>\n\n<p>That way you will fire JavaScript after you click and it won't interfere with the ASP <code>OnClick()</code> event.</p>\n"}, {'answer_id': 42817465, 'author': 'Bengi Besçeli', 'author_id': 1136253, 'author_profile': 'https://Stackoverflow.com/users/1136253', 'pm_score': 0, 'selected': False, 'text': '<p>I try this and so I could run an Asp.Net method while using jQuery.</p>\n\n<ol>\n<li><p>Do a page redirect in your jQuery code</p>\n\n<pre><code>window.location = "Page.aspx?key=1";\n</code></pre></li>\n<li><p>Then use a Query String in Page Load</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n    if (Request.QueryString["key"] != null)\n    {\n        string key= Request.QueryString["key"];\n        if (key=="1")\n        {\n            // Some code\n        }\n    }\n}\n</code></pre></li>\n</ol>\n\n<p>So no need to run an extra code</p>\n'}]
['https://Stackoverflow.com/questions/3713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557/']