ASP.NET postback with JavaScript
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
- The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET
receives argument 1 of __doPostBack__EVENTARGUMENT
receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
- As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
- If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (
javascript:__doPostBack('ButtonB','')
, then the button click handler for that button will be run.
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
- What if I don't know the ID of the control whose click handler I want to run?
- If it is not acceptable to set
ClientIDMode="Static"
, then you can do something like this:__doPostBack('<%= myclientid.UniqueID %>', '')
. - Or:
__doPostBack('<%= MYBUTTON.UniqueID %>','')
- This will inject the unique id of the control into the javascript, should you wish it
- If it is not acceptable to set
trigger automatic postback in javascript
You can have such code and place it anywhere:
<% if (!Page.IsPostBack) { %>
<script type="text/javascript">
window.onload = function() {
__doPostBack("<%= button.ClientID %>", "");
}
</script>
<% } %>
Assuming you're using C# - if you have VB.NET the syntax will be bit different.
Edit: to avoid using <%
and %>
you can have this in the Page_Load of your page:
if (!Page.IsPostBack) {
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "auto_postback", "window.onload = function() { __doPostBack(\"" + button.ClientID + "\", \"\"); }; ", true);
}
Edit II: alternative way with better chance of working is to have such JS code instead:
"window.onload = function() { var buttonID = '" + button.ClientID + "'; alert('ID: ' + buttonID + ', clicking...'); document.getElementById(buttonID).click(); }; "
This will hopefully show you the client ID of the button then auto click it. If no luck make sure the ID is correct and really exist in the document and we'll try to find what is the problem.
Execute C# Function and Postback from JavaScript
Mark Up
<asp:Button ID="btn" runat="server" style="display:none;" OnClick="Btn_Click"/>
This button will be hidden. It will be useful to perform a click and in code behind call the function in it's handler. Now in the handler write the code to call your c# method.
Java Script
Perforing the click of hidden button.
<script language="javascript" type="text/javascript">
function PerformClick() {
document.getElementById('<%=btn.ClientID %>').click();
}
</script>
Code Behind
protected void btn_Click(object sender, EventArgs e)
{
GetComplete();
}
Do something javascript before asp.net anypostback
I find the way, in the asp.net forums and it was a some code in codebehind.
Just add this to your Page_Load event handler, changing the javaScript string to what you want to happen.
string scriptKey = "OnSubmitScript";
string javaScript = "alert('RegisterOnSubmitStatement fired');";
this.ClientScript.RegisterOnSubmitStatement(this.GetType(), scriptKey, javaScript);
Run javascript function after Postback
You can use the ClientScriptManager to make a call to a function on the reload:
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
How to postback server by JavaScript Asp.net
Add an onclick="(javascript:__doPostBack('','');"
attribute to the <a>
tag to perform a postback via Javascript. Like this:
+ "<a href=\"#\" class=\"button mycoblue\" onclick=\"(javascript:__doPostBack('','');\">Kết bạn</a>"
More details here
Response to comment:
Try creating a button on the page<asp:Button ID="btnPlaceHolder" Visible="False" runat="server" />
and then do what I said in this solution but instead use __doPostBack('<%=btnPlaceHolder.UniqueID %>', '')
From there, you can use the method blockPrivate Sub btnPlaceHolder_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPlaceHolder.Click
to run the code you want on postback.
Run Javascript function after postback in asp.net
In whatever event makes most sense according to your current architecture, include:
if (Page.IsPostBack) {
ClientScript.RegisterStartupScript(this.GetType(), "HideOnPostback", "$(function() { hideInsert(); })", true);
}
Page_Load
is a common place to include logic like this.
Alternatively, if you will never need whatever is classed as .hide
after they postback and they are server-side controls, you could always set them to Visible = false
.
Javascript function run after postback complete
You have to change your approach completely, as far as it is not a ajax call, it would wipe out everything on the page, and the page would get refreshed.
So what can be done in order to achieve this? you can check it in on the backend and add the script if the page is being loaded in a postback call, like this:
if (IsPostBack)
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowWindowX",
"ShowWindowX();", true);
Of course it can be done if you already registered the script which the ShowWindowX
is defined in it.
But if you don't want it to show the window EVERY time a post back occurs, you can set a flag in a global storage like localStorage, then check it when you want to open the window:
btnBBHistory.OnClientClick = "__doPostBack();localStorage.callwin=true;return false;"
and in the server side page load do this:
if (IsPostBack)
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowWindowX",
"if(Boolean(localStorage.callwin)){ShowWindowX();localStorage.callwin='';}",
true);
How to call postback using javascript on ASP.NET form
ASP.NET already creates a client side javascript method __doPostBack to support postback.
Example: __doPostBack('__Page', 'MyCustomArgument');
Related Topics
Dynamic Function Name in JavaScript
JavaScript Url Decode Function
Regex Using JavaScript to Return Just Numbers
Palindrome Check in JavaScript
Using Jquery to Replace One Tag with Another
Idiomatically Find the Number of Occurrences a Given Value Has in an Array
How to Process Each Letter of Text Using JavaScript
Reactjs: Maximum Update Depth Exceeded Error
How to Query Referenced Objects in Mongodb
Why Does a String Index in an Array Not Increase the 'Length'
Determine Pixel Length of String in JavaScript/Jquery
$(Document).Ready(Function(){}); VS Script at the Bottom of Page
How to Delay a Function Call for 5 Seconds
Alternative to a Million If Statements
How to Replace Remapcolums with Remapcolumnsbyname in Free Jqgrid
React-Router Scroll to Top on Every Transition