3

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.

Hashir Sarwar
  • 1,115
  • 2
  • 14
  • 28

2 Answers2

2

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%>','')
Sean T
  • 2,414
  • 2
  • 17
  • 23
  • after returning true, how it will get into `Btn_Click` function? i didn't specify it anywhere. – Hashir Sarwar Nov 28 '18 at 16:36
  • It's been a while since I did webforms so as I say that may be incorrect. you may have to specify `onclick` attribute in addition to `onclientclick`. Anyhow the first part of the answer is correct – Sean T Nov 28 '18 at 16:39
  • I just recall that if you return true on client click it will go to the server click event, and since it's a submit button this will be posted – Sean T Nov 28 '18 at 16:40
  • @HashirSarwar just put a click attribute on the button then that calls the server side function and `return false` under your `write all fields` line – Sean T Nov 29 '18 at 09:39
2

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.