Javascript – How to use __doPostBack()

asp.netcjavascriptpostback

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.

Best Answer

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.