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

不羁岁月 提交于 2019-12-11 04:54:11

问题


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.


回答1:


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%>','')



回答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.



来源:https://stackoverflow.com/questions/53523797/dopostback-function-isnt-working-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!