Calling asp.net webmethod with params from jquery errors - asp.net

I managed to setup a simple webmethod which i called from jquery and sure enough it returns ... then i added parameters on the method and added the params to jquery but it errors with
Message":"Invalid JSON primitive: one.","StackTrace":"
my signature on my webmethod is like so
[WebMethod]
public static string GetDate(string one, string two)
{
return "yes";
}
and my jquery is like this, what am i doing wrong?
$.ajax({
type: "POST",
url: "MyService.aspx/GetDate",
data: { one: "value", two: "value" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function(msg) {
alert('error');
}
});

Try enclosing your data parameter in quotes:
data: '{ one: "value", two: "value" }',

Related

Parameters lost zeros in Ajax request

I send parameters for WebMethod with Ajax and receive um object. But, paramters lost zeros in WebMethod, i send "00001234", in backend paramenters is "1234"
Ajax Code:
var content = {valueS: "00001234" };
$.ajax({
type: "GET",
dataType: 'json',
data: content,
async: false,
url: "myPage.aspx/GetData",
contentType: "application/json; charset=utf-8",
success: function (data) { OnSucess(data); },
error: function(data) { OnError(data); }
});
Webmethod Code:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static string GetData(string valueS)
{...}
Try
var content = {valueS: "'00001234'" };
$.ajax({
type: "GET",
dataType: 'json',
data: content,
async: false,
url: "myPage.aspx/GetData",
contentType: "application/json; charset=utf-8",
success: function (data) { OnSucess(data); },
error: function(data) { OnError(data); }
});
seems valueS is being deserialized to a number first, in which case it will loose its leading zeros.
The request generated by your code looks like this myPage.aspx/GetData?valueS=00001234
while the one generated by my code looks like this myPage.aspx/GetData?valueS=%2700001234%27, hence will be correctly deserialized as a string.

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

ASP.NET hello world AJAX post

I keep getting a 500 with the following C#/jQuery. Any given implementation may not be right and thats not a huge issue. I'm just trying to get a hello world up. It works if the c# has no arguments but as soon as I try to recieve data it gives the 500.
[WebMethod]
public static string Test(string s)
{
// never gets here
}
$.ajax({
type: "POST",
url: "ajax.aspx/" + method,
/*async: true,*/
data: "{data:'" + data + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
callback(data.d);
}
});
latest attempt is this which still doesnt work:
[WebMethod()]
public static string Test(string data)
{
// never gets here
return "hello world";
}
$.ajax({
type: "POST",
url: "ajax.aspx/Test",
data: "data: {data:'abc'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("back");
}
});
I think you don't have to use MVC to make it work. I think the way you are passing json parameters are wrong. Please check below code and try and do let me know whether it works.
[WebMethod()]
public static string Test(string data)
{
// never gets here
return "hello world";
}
$.ajax({
type: "POST",
url: "ajax.aspx/Test",
data:'{"data":"abc"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
try this
[HttpPost]
public ActionResult Test(string x)
{
// never gets here
return Json(true)
}
$.ajax({
type: "Post",
url: "ajax/Test",
data: {x:'abc'},
dataType: "json",
success: function (data) {
alert("back");
}
});

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

asp.net page method with jquery and parameter

In my javascript, I have:
var testdate = "{'TheNewDate' : '12/02/2011'}";
$("#mydiv").click(function () {
$.ajax({
type: "POST",
url: "../Pages/Appointments.aspx/GetAppointements",
data: testdate,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
});
In my code behind I have
[WebMethod]
public static string GetAppointements(string DateInput)
{
var t = DateInput;
However, when I click to run the call, I get the error function to activate. When I change the code behind function to public static string GetAppointement() it works. But I guess my goal is to pass a parameter to the code behind. What am I missing?
Thanks.
Your parameter is called DateInput and not TheNewDate, so:
$('#mydiv').click(function () {
$.ajax({
type: 'POST',
url: '../Pages/Appointments.aspx/GetAppointements',
data: JSON.stringify({ dateInput: '12/02/2011' }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: successFn,
error: errorFn
});
});
You should make your JSON data match the parameter name in the web service method.
var testdate = "{'DateInput' : '12/02/2011'}";

Resources