Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...