__doPostBack() function isn't working (asp.net)

3.3k Views Asked by At

I am trying to trigger button event from the JS code. But doPostBack in JS function reg() is not directing to the c# code. Please tell me what's wrong. Here is my code:

<script>
        function reg() {
            var name = document.getElementById('name').value;
            var id = document.getElementById('cnic').value;
            var age = document.getElementById('age').value;
            var ph = document.getElementById('phone').value;
            var pas = document.getElementById('pass').value;
            if (id == '' || pas == '' || age == '' || ph == '' || pas == '')
                window.alert("Write all fields");
            else {
                __doPostBack('<%= Button1.UniqueID%>','')
            }
        }
    </script>  


 <div >
       <asp:Button id="Button1" OnClientClick="reg()" runat="server" Text="Submit"/>
    </div>

Here is the server side c# function associated with the button:

 protected void Btn_Click(object sender, EventArgs e)
    {
        Button clickedButton = (Button)sender;
        clickedButton.Text = "...button clicked...";
    }

Note: In else block, I want reg() function to redirect to the Btn_Click function.

2

There are 2 best solutions below

4
On

It's been a while since I did this, but I think it needs to be the server Id, not client id of the button.

 __doPostBack('<%= button1.UniqueID%>','')
0
On

Looks like you are missing the OnClick in asp:Button.

<asp:Button id="Button1" OnClientClick="reg()" runat="server" Text="Submit" OnClick="Btn_Click"/>

There is a in-built method in ASP.NET to generate the __doPostBack() method.

<%= Page.ClientScript.GetPostBackEventReference(Button1, String.Empty) %>; 

If still not working after the changes, I would suggest you to check the network traffic using Network tab of browser Debug tools(or Fiddler) when you click on the button.

Also set a break point inside the reg() method to see how the control goes.