I would like to pass parameters to my webservice from jquerys ajax. How can I do that?
I’ve already looked through a few of the related questions but couldn’t find a solution that worked for me. I’ve tried this: jQuery AJAX parameter not being passed to MVC but I’m not using mvc so I’m sure that is why the solution isn’t working.
My jquery looks like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CarService.svc/GetCar",
data: {CarID:117},
dataType: "json",
success: function (data) {
$("#lblCurrentTime").text("");
$("#lblCurrentTime").text(data.d.CarID);
}
});
Something is wrong with my ‘data’ part, correct? If leave the data: part as data: “{}” I can get my method to run (and I don’t pass any parameter) but the moment I try the above out firebug tells me:
Firebug's log limit has been reached. 0 entries not shown. Preferences
POST http://localhost:64461/TimeService.svc/GetCar
POST http://localhost:64461/TimeService.svc/GetCar
500 Internal Server Error
1.12s
My Webservice looks like this:
[OperationContract]
public CarTable GetCar(int id)
{
using (var sqlc = new SqlConnection(@"sdfgsdfg"))
{
sqlc.Open();
var cmd = sqlc.CreateCommand();
cmd.CommandText = "HUGE QUERY HERE ^^";
//id = 117;
cmd.Parameters.Add("CarID", System.Data.SqlDbType.Int).Value = id;
using (var reader = cmd.ExecuteReader())
{
CarTable Cars = new CarTable();
while (reader.Read())
{
Cars.CarID = reader["CarID"].ToString();
Cars.CarName = reader["CarName"].ToString();
}
return Cars;
}
}
}
[DataContract]
public class CarTable
{
[DataMember]
public string CarID { get; set; }
[DataMember]
public string CarName { get; set; }
}
EDIT: If I change the data part to:
data: CarID=117,
I get Sys.ParameterCountException: Parameter count mismatch.
[Break On This Error] {name: “format”, type: String}
First you should verify that you include attribute
to the
GetCarmethod or do the same in web.config.Second you should use
data:"117"ordata:JSON.stringify(117)instead ofdata: {feat:117}.UPDATED: If you would has a more complex data input, for example as an object
CarTablethedataparameter should bedata:JSON.stringify({CarID: 117, CarName: "BMW"}), so it should be built in the same way. TheJSON.stringifyis defined in http://www.json.org/js.html.One more remark. After the successful return of data you will see that the data returned back should be accessed not with
data.d.CarID, but withdata.CarIDinstead. ASMX web-service place the data in the propertyd, but not WCF service.UPDATED 2: I don’t know which small error you do, so I created a small WCF service which do what you need. You can download the source code here http://www.ok-soft-gmbh.com/jQuery/WcfData.zip. To be sure that you will be able compile it I used Visual Studio 2008. In Visual Studio 2010 the web.config file can be much more simple.