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

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) {}
});

Related

Ajax function failing to hit method on code behind on server

I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:

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[]

Ajax URL - Incorrect .net #c

Been following some tutorials, as i'm learning C#, however was just attempting to make an ajax call to the server, i'm using my localhost.
As far as I can tell i'm doing its right, but it's obviously not.
Maybe it my folder structure or just the name of the file.
The Default.aspx file is at the project root
Here is my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx",
dataType: "json",
data: "{'FirstName':'test','LastName':'test1','City':'test3','EmailID':'test4'}",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});
I know eventually it will have to call a method within the file, but its not even finding it at the moment.
Thanks in advance, James
You can use controller Home and create the one action.
Example:
public ActionResult FirstAjax()
{
return Json(true, JsonRequestBehavior.AllowGet);
}
After that your jquery ajax is:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "Home/FirstAjax",
dataType: "json",
data: "",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});

Unable to pass data to method

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)},

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});

Categories