Is there a way to get an ASMX Web Service created in VS 2005 to receive and return JSON?
- by Ben McCormack
I'm using .NET 2.0 and Visual Studio 2005 to try to create a web service that can be consumed both as SOAP/XML and JSON. I read Dave Ward's Answer to the question How to return JSON from a 2.0 asmx web service (in addition to reading other articles at Encosia.com), but I can't figure out how I need to set up the code of my asmx file in order to work with JSON using jQuery.
Two Questions:
How do I enable JSON in my .NET 2.0 ASMX file?
What's a simple jQuery call that could consume the service using JSON?
Also, I notice that since I'm using .NET 2.0, I i'm not able to implement using System.Web.Script.Services.ScriptService.
Here's my C# code for the demo ASMX service:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class StockQuote : System.Web.Services.WebService {
public StockQuote () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public decimal GetStockQuote(string ticker)
{
//perform database lookup here
return 8;
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
Here's a snippet of jQuery I found on the internet and tried to modify:
$(document).ready(function(){
$("#btnSubmit").click(function(event){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://bmccorm-xp/WebServices/HelloWorld.asmx",
data: "",
dataType: "json"
})
event.preventDefault();
});
});