简体   繁体   中英

onclick and onclientclick webmethod executed after onclick

I am trying to set a variable on using a webmethod ( .asmx )

The button is using onclick to call a server side method and onclientclick to call a javascript ajax which calls the webmethod.

I need the javascript code to be fully executed before the onclick server end method is called, but it seems as though the ajax call is not fully being executed before the postback is being made.

The alert is called before postback however the webmethod is being called after the postback. I need the variable to be set from the webmethod before the postback is done. I have tried returning a false from the javascript but then postback isnt being done at all.

I am using Masterpages in asp.net. Also I have a similar function in another project which works fine, the only difference is in this one I'm using a MasterPage.

<asp:TemplateField>
<ItemTemplate>
    <asp:Button ID="btnAddRegistration" ClientIDMode="Static" CssClass="btn-sm btn-default" runat="server"
        CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
        onclick="btnAddRegistration_Click"
        OnClientClick='<%# "getSetContactID(\"" + Container.DataItemIndex + "\")" %>'
        Text="Add &#010;Registration" />
 </ItemTemplate>
</asp:TemplateField>

Javascript (call to webmethod)

 function getSetContactID(rowIndex) {

    var CellValue, cell, dataItemIndex;
    var table = document.getElementById('<%=gvContactSearch.ClientID %>');

    $.ajax({
        type: "POST",
        url: "WebService1.asmx/setContactIDgvContact",
        data: '{DataItemIndex: "' + rowIndex + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: alert(rowIndex), <--this gets called before postback
        failure: function (response) {alert(response.d);}

        })
 }

Webservice method

 [WebMethod]
        public string setContactIDGV1(int DataItemIndex){
           classDetails.gV1DataItemIndex = DataItemIndex; 
           return "";
        }

What you have here is a classic race-condition scenario.

By default an AJAX call is asynchronous, so when you fire an AJAX call the JS code block logically comes to an end, and the next sequential event is fired, in this case your server side event. It's then a race between the function that the AJAX code has executed and your server-side onclick event. The way I see it you have a few options:

  1. Call your web service method inside your server-side on click method
  2. Prevent the default element action inside the JS block ( event.preventDefault ), and hook something up inside the AJAX success method that finishes the sequence
  3. Set the async: false option on the AJAX call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM