Jquery's Ajax Property For Asp.Net 2.0
-
08-07-2019 - |
Question
I always see the code like this in the blogs:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
But I think this is run only with asp.net 3.5. I couldn't run it with 2.0. How can I use such these codes in my Applications?
Solution
You need to add this attribute to your webserver class
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
and this attribute to your functions
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
You don't technically need to specify the responseformat, as it responds according to the format you specify in the request. And you must specify a format in the request.
Regards
K
OTHER TIPS
If you use jQuery to connect to the server you don't need the ScriptManager
in your HTML.
I think other part of you code is correct. Just remove the ScriptManager
.
I already know this article, but It couldn't help me.
In my sample app, I use these codes:
my Jquery code:
$(document).ready(function() {
$('#clKaydet').click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
});
My Html Code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
<div>
<input type="button" id="clKaydet" runat="server" value="Kayıt" onclick="Kayit()" />
</div>
</div>
</form>
My Webservise Code:
<WebMethod()> _
Public Function HelloWorld() As String
Dim sText As String = "Hello"
Return sText
End Function
Is there any mistake?
We use jQuery for all our DOM manipulation, but when sending data back to the server we use ASP.Net AJAX to take advantage of autogenerated proxy classes
Makes life real simple!
I think that the bit that you're missing is that a method marked with a WebMethod tag is going to serialize the data as XML, not JSON. With ASP.NET MVC you can return JSON natively, but if you want JSON for a WebMethod you may need to write your own converter. I'd suggest trying to change the datatype for the AJAX call to "xml" and see if that works.
I also don't use jquery for AJAX (yet), so I haven't tried this (yet).
In conclusion, Do You say that, I can't use these codes direktly with asp.net 2.0?