Reputation: 6400
I have a WebMethod in my code behind I'm calling via AJAX. The method works when using a GET request but I'd prefer to use POST and I'd also like to know why this doesn't work and/or what I'm doing wrong.
JavaScript
$(document).ready(function () {
$.ajax({
url: "Default.aspx/HelloWorld",
method: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#test1").html(data.d);
},
error: function (err) {
$("#errOutput").text("ERROR: " + err.responseText);
}
});
});
C#
[WebMethod]
[ScriptMethod(UseHttpGet=false)]
public static string HelloWorld()
{
return "Hello World!";
}
Error
Message:
"An attempt was made to call the method \u0027HelloWorld\u0027 using a
GET request, which is not allowed.",
StackTrace:
"at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)\r\n
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData methodData)",
ExceptionType:"System.InvalidOperationException"
Upvotes: 0
Views: 2247
Reputation: 1500785
Looking at some jQuery documentation I think you're using the wrong property. I suspect this:
method: "POST"
should be
type: "POST"
method
feels like the more sensible name to me too, but there we go...
(Disclaimer: I've never used jQuery myself... this answer is purely based on the docs.)
Upvotes: 2