Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

javascript - Calling server side event in asp.net from java script

Surely will be marked as duplicate one but after tons of question and example i couldn't solve my problem.
What i want?
Calling server side event handler in asp.net from client side java script it is not going on server side. I checked it by setting breakpoint, the page flicks but server side method is not called.
My click event on code behind is

  protected void btninsert_Click(object sender, EventArgs e)
  {
      // my code
  }

aspx file

   <asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
      OnClientClick="DoPost()" Text="Save" />

Javascript method is

   function DoPost() {
        function DoPost() {
        var chk = document.getElementById('<%= chkstatus.ClientID %>');
        if (chk.checked)
            __doPostBack('<%= btninsert.ClientID %>', 'OnClick');
        return true;
        //return false;
    } 
    } 

I also tried this __doPostBack('btninsert', 'OnClick'); and __doPostBack('btninsert', ''); and $('btnSubmit').trigger('click'); with no success.

What am i doing wrong?

Edit: If i uses OnClick event then it is going in the server side event irrespective of the if condition in the DoPost method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ahh it was simple. Thanks to all answers.
Solution:
Use OnClick attribute for server side event and OnClientclick for client event for validation. OnClientClick javascript method will return true and false which decides whether serverside onclick event will fire or not.
Code will be somthing like this

  <script type="text/javascript">
    function DoPost() {
        var chk = document.getElementById('<%= chkstatus.ClientID %>');
        if (chk.checked) {
            var c = confirm("are you sure?");
            if (c == true) {
                return true;
            } else
            { return false; }
        }
        return true;
    } 
</script>

And the Button tag

<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
   OnClientClick="return DoPost();" OnClick="btninsert_Click" Text="Save" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...