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 
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 "";
}