JQuery Ajax Property for Asp.Net 2.0
I always see code like this on 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 only runs with asp.net 3.5. I couldn't start it from 2.0. How can I use such codes in my Applications?
source to share
You need to add this attribute to your web server
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
and this attribute for your functions
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Technically, it is not necessary to provide a response form as it responds to the format specified in the request. And you have to specify the format in the request.
Best regards
K
source to share
I already know this article, but it couldn't help me.
In my sample application, I am using the following 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 Webservice code:
<WebMethod()> _
Public Function HelloWorld() As String
Dim sText As String = "Hello"
Return sText
End Function
Is there a mistake?
source to share
I think the bit you are missing is that a method tagged with the WebMethod tag will serialize the data as XML, not JSON. With ASP.NET MVC, you can return JSON natively, but if you want JSON for WebMethod, you may need to write your own converter. I would 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 it yet (yet).
source to share