ASP.NET 4.0 - Using Jquery, how do I call a codebehind function and return data to the client?
When I click on the following div:
<div id="Result">Click here for the time.</div>
I need the following codebehind function to run:
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
I need this to populate the inside of the div with the string returned by the GetDate() function. I think this should use code similar to this:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").cli开发者_开发问答ck(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
</script>
I've pulled this example from this site: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
However, I simply cannot get it to work. Nothing happens. This is just a regular asp.net web project. I haven't done any sort of Ajax-enabling business other than including script tags in my markup to reference jquery.
Here's what the firebug console tells me when I click on the div:
POST http://admin/Default.aspx GetDate 404 Not Found -18ms
Edit: Note: test.aspx/GetDate must match your aspx page name and function name!
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
Gotta be "Shared" ("static" in C#)
精彩评论