ASP.NET jQuery - how to invoke server method when asynchronous method is complete?
I have jQuery plugin - progress bar. How to invoke server side method on success? The code is below:
(Everything works fine)
$("#<%=this.btnGetData.ClientID%>").click(
function () {
intervalID = setInterval(updateProgress, 100);
$.ajax({
type: "POST",
url:开发者_StackOverflow "ProgressBar.aspx/ExecuteImport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg)
{
//HERE should be invoke
}
});
return false;
}
);
As we've established this in WebForms then you can use an ASP.NET AJAX callback to a web method placed in your aspx file.
First, create your server side method in C# (or .NET language of choice) and annotate it with the ScriptMethod and WebMethod attributes, like so:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static void MyServerMethod(string myArgument)
{
// Do something
}
Then in your aspx file you need to add a ScriptManager with PageMethods enabled:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Then call it from your jQuery success event:
success: function (msg)
{
PageMethods.MyServerMethod(msg);
}
I'm basing this on my Hidden Features of ASP.NET answer here (which is not jQuery specific). However, for more details about using jQuery with WebMethods have a read of Using jQuery to directly call ASP.NET AJAX page methods.
For the VB fans out there, here is my implementation of Dan's answer above:
<script type="text/javascript" >
function EmailManagers_Click() {
PageMethods.EmailManagers("hello");
return false;
}
</script>
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Sub EmailManagers(myArgument As String)
Dim x = myArgument
End Sub
精彩评论