Unable to pass data to method - c#

I am trying to use AJAX with ASP.NET for the first time - by trying to pass the following data to a WebMethod in my corresponding aspx page:
$.ajax({
type: "POST",
url: "myurl.aspx/SaveScreen",
data: "{'data': " + JSON.stringify(arrayRows.data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
Here is my WebMethod in the aspx page. I have tried passing a simple data object which just contained one key and value, which worked successfully. When attempting to pass this object, I get an error stating that there is an internal server error with code 500.
What could I be doing wrong?

Try this:
data: {"data": JSON.stringify(arrayRows.data)}

Try this :
data: "{data: '" + JSON.stringify(arrayRows.data) + "'}"

You could wrap the data string in quotations:
$.ajax({
type: "POST",
url: "SpecifyPositioning.aspx/SaveScreen",
data: "{'data': '" + JSON.stringify(arrayRows.data) + "'}", //Added ' around JSON.stringify to pass string instead of object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
This however would be a cleaner solution:
data: {"data": JSON.stringify(arrayRows.data)},

Related

How to pass array as an argument to server method via jQuery+Ajax

Well I am developing a web application in Asp.Net and in the code behind I am using C#. I've successfully written code to pass a class object to code behind method but I am wondering how to pass an array as an argument via ajax and jQuery.
I've tried something but it didn't work. Here is my code what I am trying to run
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: '{args: ' + argu + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
And this is my code behind method which is written in C#.
[WebMethod]
[ScriptMethod]
public static bool Foo(int[] args)
{
return true;
}
Application built successfully. I have put break points but my code behind method doesn't fire. I am wondering Where is the problem? What else I am missing here?
Well all code seems good enough to make a call but I think the problem is in passing the data in your code.
It should be like.
data: '{args: ' + JSON.Stringify(argu) + '}'
And finally your code should be like
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: '{args: ' + JSON.Stringify(argu) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
Hope that helps.
Where is the problem?
What you are sending is not valid JSON and that's what you are telling $ajax to send when you set contentType: "application/json; charset=utf-8"
JSON requires double quotes for keys and for string values
Don't try creating JSON manually ... use language built in serializers
Try changing:
data: '{args: ' + argu + '}',
To
data: JSON.stringify({args: argu }),
Note: Seems you are expecting int in server code. Looks suspicious when you are sending an object structure
Why no simply set the array value to data and do the post ?
function Test(){
var argu = [1, 2];
$.ajax({
type: 'POST',
url: 'MyPage.aspx/Foo',
data: argu,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Success
},
error: function (response) {
// Failed
}
});
}
You can use JSON.stringify([1,2]) to send the entire data as a string to the backend, get the data as a string (rather than int[]) and deserialize of parse it back to int[]

ASP.NET Ajax jquery input parameter is null

I have a problem with this.
below are my jquery code and aspx.cs code.
I should send $('#UserID').val() to WebMethod as a parameter.
but in WebMethod it is always null.
if I change $('#UserID').val() to any string, it works well.
#UserID is correct. because I made a alert window with this value.
and.. I already changed data: '{userId: "' + $('#UserID').val() + '"}',
to data: JSON.stringify({ userId: $('#UserID').val() }).
but nothing works.
$.ajax({
url: "register.aspx/IsIdAvailable",
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{userId: "' + $('#UserID').val() + '"}',
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
})
[WebMethod]
public static bool test(string userId)
{
System.Diagnostics.Trace.WriteLine("userId: " + userId +"!");
...
}
output is always userId: !
Try changing your data attribute to something like:
data: {'userId': $("#UserID").val()}

how to properly send JSON via ajax to c# [WebMethod]?

I want to send a JSON string via ajax to [WebMethod]. My JSON values contain double quotation marks ("). In js, I create an object and convert it to JSON with JSON.stringify(my_object). Console shows properly formatted JSON (double quotes are masked with \), jsonlint.com confirms it.
But the problem appears in [WebMethod]. After hours of debugging I found out that it ignores masked " and treats them as normal ". So my properly JSON-formatted string becomes not properly JSON-formatted string.
Is there a way to fix this? Changing my input string is not an option (I mustn't get rid of ").
Here's some code:
ajax request:
$.ajax({
type: 'POST',
url: 'Test_Page.aspx/Test',
data: "{json: '" + JSON.stringify(json_string) + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {},
error: function (msg) {}
});
web method:
[WebMethod]
public static string Test(string json) {
return Newtonsoft.Json.JsonConvert.SerializeObject(Other_Function(json));
}
Try this:
$.ajax({
type: 'POST',
url: 'Test_Page.aspx/Test',
data: JSON.stringify({json: json_string}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {},
error: function (msg) {}
});

Access C# method using ajax in asp.net?

Below are both my C# and
JavaScript code, I can access this method but I'm not getting the expected output
from "success":
success: function( msg ){
alert( msg.d );
}
Instead it returns [object object]
Javascript:
$.ajax({
type: "POST",
url: "Home.aspx/UpdateSelectionStatus,
data: '{id_ver: "' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg){alert(msg.d);},
failure: function(){ }
});
C#:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string UpdateSelectionStatus(string id_ver){
return "success" + id_ver;
}
That is the bug:
alert(msg.d);
just use msg directly:
success: function (msg) {alert(msg); },
You returned a simple string, not a complex type, so you haven't got any property like "d".
Please try below code: it is working at my end.
var vid = 10;
$.ajax({
type: "POST",
url: "/Home.aspx/UpdateSelectionStatus",
data: "{id_ver:'" + + vid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
success: function( msg ){
alert( msg.d.toString());
}

jQuery.ajax "data" parameter syntax

I am trying to pass the contents of a javascript variable to the server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code:
(Client)
function expand(checkbox)
{
var selectedrow = checkbox.parentNode.parentNode;
var rowindex = selectedrow.rowIndex;
var parent = document.getElementById("parentTable");
var NextRow = parent.rows[rowindex + 1];
var cols = selectedrow.cells[1];
var ID = cols.firstElementChild.attributes.value;
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: "{sendData: ID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
NextRow.style.visibility = "visible";
}
(Server)
[WebMethod]
public static string childBind(string sendData)
{
return String.Format("Hello");
}
Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?
You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.
Try this
data: { sendData: ID }
You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: {sendData: ID},
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
You can also write this, if you want to send JSON:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: $.getJSON({sendData: ID}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) { alert("successful!" + result.d); }
})
Since you are using jQuery run these tests for the answer:
var ID = 45;
var x = "{sendData: ID}";
alert(jQuery.isPlainObject(x)); // false
var y = { sendData: ID};
alert(jQuery.isPlainObject(y)); // true
Here is the jsFiddle:
http://jsfiddle.net/3ugKE/
You are passing in 'ID' as a string rather than a variable.
All you need to do is remove the quotes around your data object.
Further reading on JSON and javascript objects:
http://www.json.org/
http://www.w3schools.com/js/js_objects.asp
you can use this code :
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: JSON.stringify({sendData: ID}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})

Categories