173

I'm trying to create an asyncrhonous postback in ASP.NET using __doPostBack(), but I have no idea how to do it. I want to use vanilla JavaScript.

Something simple like a button click can cause the __doPostBack() event to fire. I'm just trying to learn how the mechanism works.

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Michael Kerute
  • 1,751
  • 2
  • 11
  • 5
  • possible duplicate of [Asychnronous Message Send Asp.net](http://stackoverflow.com/questions/3589414/asychnronous-message-send-asp-net) – Kris van der Mast Aug 28 '10 at 17:19
  • 10
    First of all __doPostBack doesn't cause asynchronous action unless it is triggered by control inside UpdatePanel. – Ladislav Mrnka Aug 28 '10 at 17:37
  • Why is this tagged [tag:c#] and [tag:javascript]. I understand the [tag:javascript] part, but not the [tag:c#] part. – Solomon Ucko Jun 11 '16 at 01:27
  • 2
    @Solomon Ucko - because __doPostBack() causes the page to POST to its server-side implementation, which will most likely be in C# (could be VB.NET) – sh1rts Dec 22 '16 at 04:33
  • 2
    While it usually works, manually inserting `__doPostBack` is not actually supported. If your page has nothing on it which triggers a postback, asp.net might omit defining the `__doPostBack` function. The supported approach is to call `ClientScriptManager.GetPostBackEventReference`, which returns a string in the form `__doPostBack(...)` and ensures that `__doPostBack` is defined. – Brian Jul 09 '19 at 20:53

7 Answers7

171

You can try this in your web form with a button called btnSave for example:

<input type="button" id="btnSave" onclick="javascript:SaveWithParameter('Hello Michael')" value="click me"/>

<script type="text/javascript">
function SaveWithParameter(parameter)
{
  __doPostBack('btnSave', parameter)
}
</script>

And in your code behind add something like this to read the value and operate upon it:

public void Page_Load(object sender, EventArgs e)
{
  string parameter = Request["__EVENTARGUMENT"]; // parameter
  // Request["__EVENTTARGET"]; // btnSave
}

Give that a try and let us know if that worked for you.

codingbiz
  • 26,179
  • 8
  • 59
  • 96
Mr. Mr.
  • 4,257
  • 3
  • 27
  • 42
  • 2
    Just a quick question, __EVENTARGUMENT would be the parameter or btnSave? – harsimranb Sep 03 '12 at 23:08
  • 4
    It is the parameter. __EVENTTARGET will give you the button. – Mr. Mr. Sep 04 '12 at 08:18
  • what if i have two or more buttons that do __doPostBack then how do i differentiate them on server side in page_load(). – khalid khan Jun 08 '14 at 06:40
  • @khalidkhan if you are implementing your JavaScript as I have demonstrated then the __EVENTTARGET will still apply, depending on which button you clicked you would have a different value represented by __EVENTTARGET – Mr. Mr. Jun 09 '14 at 13:12
  • 1
    What is the case when i have more than one parameter? – Wilson Sep 15 '14 at 07:16
  • @Wilson you could try passing in an array and reading it as a form of `IEnumerable` instead of `string` in the C#, I have not tried so cannot guarantee it would work, but it should be possible. – Mr. Mr. Sep 18 '14 at 13:29
  • 1
    @Wilson as another thought your argument could be Json data which could map to an object in your C#, you could then use Json.net to deserialise/serialise to object etc. – Mr. Mr. Sep 18 '14 at 13:32
  • @khalidkhan Instead of explicitly specifying the id of the button, as shown in the answer, specify event.target.id.ClientID without quotes, and the correct ID that caused the event will be inserted. – erict Jan 05 '20 at 01:56
27

This is also a good way to get server-side controls to postback inside FancyBox and/or jQuery Dialog. For example, in FancyBox-div:

   <asp:Button OnClientClick="testMe('param1');" ClientIDMode="Static"  ID="MyButton"  runat="server" Text="Ok" >
</asp:Button>

JavaScript:

function testMe(params) {
    var btnID= '<%=MyButton.ClientID %>';          
    __doPostBack(btnID, params);
}

Server-side Page_Load:

 string parameter = Request["__EVENTARGUMENT"];
 if (parameter == "param1")
     MyButton_Click(sender, e);
user2775317
  • 271
  • 3
  • 3
16

Here's a brief tutorial on how __doPostBack() works.

To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button, LinkButton, ImageButton, parts of the GridView, etc.) use __doPostBack as their post back mechanism.

Tyzoid
  • 1,072
  • 13
  • 31
kbrimington
  • 25,142
  • 5
  • 62
  • 74
  • Fast forward 6 years later; I will be shocked if still use this. The approach towards web development has generally moved away from the mentality where things like this are used. – Phil Sep 21 '16 at 16:10
  • @Phil - haha, I was reading this thread yesterday while looking at a bug where this was implemented :) It does seem quite archaic in this day and age – Terry Delahunt Sep 23 '16 at 15:45
  • 14
    Fast forwarded 6 years... and ASP.NET Web Forms does still do this. Hence the overwhelming upvoting of the accepted answer. – kbrimington Sep 25 '16 at 20:24
  • @kbrimington: I did not say ASP.NET will not "still do this". I do not expect it to change much. What I meant is that less people use ASP.NET WebForm for new development and others are migrating off it. – Phil Sep 27 '17 at 22:06
15

I'd just like to add something to this post for asp:button. I've tried clientId and it doesn't seem to work for me:

__doPostBack('<%= btn.ClientID%>', '');

However, getting the UniqueId seems to post back to the server, like below:

__doPostBack('<%= btn.UniqueID%>', '');

This might help someone else in future, hence posting this.

Polynomial Proton
  • 5,020
  • 20
  • 37
5

Old question, but I'd like to add something: when calling doPostBack() you can use the server handler method for the action.

For an example:

__doPostBack('<%= btn.UniqueID%>', 'my args');

Will fire, on server:

protected void btn_Click(object sender, EventArgs e)

I didn't find a better way to get the argument, so I'm still using Request["__EVENTARGUMENT"].

Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
2

Like others have said, you need to provide the UniqueID of the control to the __doPostback() method.

__doPostBack('<%= btn.UniqueID %>', '');

On the server, the submitted form values are identified by the name attribute of the fields in the page.

The reason why UniqueID works is because UniqueID and name are in fact the same thing when the server control is rendered in HTML.

Here's an article that describes what is the UniqueID:

The UniqueID property is also used to provide value for the HTML "name" attribute of input fields (checkboxes, dropdown lists, and hidden fields). UniqueID also plays major role in postbacks. The UniqueID property of a server control, which supports postbacks, provides data for the __EVENTTARGET hidden field. The ASP.NET Runtime then uses the __EVENTTARGET field to find the control which triggered the postback and then calls its RaisePostBackEvent method.

src: https://www.telerik.com/blogs/the-difference-between-id-clientid-and-uniqueid

jBelanger
  • 1,526
  • 18
  • 11
0

This is how I do it

    public void B_ODOC_OnClick(Object sender, EventArgs e)
    {
        string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);               
    }