Send complex data to C# with jQuery - c#

I have a JavaScript object like so that I want to send to C# (question right at the bottom)
var data = {
mykey1: "somevalue",
mykey2: "somevalue2",
addProducts: [
{
id: 1,
quantity: 3,
variation: 54
},
{
id: 2,
quantity: 5,
variation: 23
}
]
}
It is to add either a single product or multiple products to a users basket. I want to send an array of objects back..
I can access this in Javascript by using
data.addProducts[1].id
using the below...
$.ajax({
url: "/ajax/myurl",
data: data,
dataType: "json",
type: "GET",
success: function( response ){
// Data returned as JSON
}
});
it is sending the data like this (URLdecoded for your reading pleasure)
?mykey1=somevalue&mykey2=somevalue2&addProducts[0][id]=1&addProducts[0][quantity]=3&addProducts[0][variation]=54&addProducts[0][id]=2&addProducts[0][quantity]=5&addProducts[0][variation]=23
My question is... without using JSON.stringify on the data, which will just send it as a full object in the url /ajax/myurl/{mykey1:1 ...}
How can I read this information back in from C#? jQuery is just encoding it as the standard way, should I be doing anything else to this, and is there a built in way to grab this data in C#?

var strValue = $(getStringValue);
var intValue = $(getIntValue)
$.ajax({
type: \"post\",
url: \"default.aspx/getData\",
data: \"{\'postedAjaxStringValue\"\': \'\" + encodeURIComponent(strValue) + \"\', postedAjaxIntValue: \" + encodeURIComponent(intValue ) + \"}\",
contentType: \"application/json; charset=utf-8\",
dataType: \"json\",
success: OnSuccess,
failure: function (response) {
error: function (response) {
});
//ON C# KodeBehind..
[System.Web.Services.WebMethod]
public static string getData(string postedAjaxStringValue, int postedAjaxIntValue){}

Related

C# and Ajax - Posting 2 values from JS to C#

I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}

Ajax cannot read Serialized Json dictionary correctly

This is what I have in my c# code
using Newtonsoft.Json;
.....
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("id", id.ToString());
d.Add("type", "error");
d.Add("msg", pex.Message);
.....
return JsonConvert.SerializeObject(d);
My AJAX
......
$.ajax({
type: "POST",
url: "Service1.svc/MyCall",
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
beforeSend: function () {
$("#lblResult").html("loading");
},
success: function (data) {
$("#lblResult").html(data['id']);
},
......
This is the response in Firebug
"{\"id\":\"1\",\"type\":\"error\",\"msg\":\"An exception occurred during a Ping request.\"}"
This is the JSON in Firebug
0 "{"
1 """
2 "i"
3 "d"
4 """
5 ":"
6 """
7 "1"
8 """
9 ","
10 """
11 "t"
ETC
Problem: I cannot get data['id'] or any data['SOMETHING'].
How can I get it based on the response received?
Any other way to do all?
This looks like the JSON is not being converted back to a JavaScript object correctly. Try this
success: function (data) {
if (data.hasOwnProperty("d"))
{
var response = JSON.parse(data.d);
$("#lblResult").html(response["id"]);
}
else
{
var response = JSON.parse(data);
$("#lblResult").html(response["id"]);
}
}
The .d is required as .Net adds this for security reasons, a better explanation than I can give can be found here Why do ASP.NET JSON web services return the result in 'd'?.
Then since the returned value is a JSON string, this needs to be parsed to become the Javascript Object

JavaScript - extracting data from a JSON object created with Json.Net

I have a server-side method used to return the data to the user. The data is stored in a SQL Server database and is mapped using EF 6. Once extracted from the database using an id value, the object is subsequently serialized using the Json.NET framework. The object is used "as is", without filtering out the references to other tables. Because of that, I've had to use the "PreserveReferencesHandling" option.
On the client-side, AJAX is used to call the method. I'm having trouble extracting the data from the object (client-side) which does get serialized and is delivered to the browser as expected.
Server-side method:
[WebMethod]
public static string ContactData(long id)
{
IService<Contact> contactService = new ContactService();
Contact contactEdit = contactService.GetById(id);
string str = JsonConvert.SerializeObject(contactEdit, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
return str;
}
Client-side function (the important part):
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact) {
$("#tbFirstName").val(contact.d[0].Contact.first_name); // I've tried various combinations to no avail
},
});
This is how the JSON object (testing purposes data) looks like in Visual Studio's JSON Visualizer:
And this is what the browser (FF 32, it that matters) receives:
Firebug
I will post more info if needed.
First parse the json before you process it. and loop through it using jquery each function.
$.ajax({
type: "POST",
url: "Contacts.aspx/ContactData",
data: JSON.stringify({ id: contactId }), // id by which I am receiving the object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (contact)
{
var contact=jQuery.parseJSON(contact);
$.each(contact, function(i, item) {
alert(i + " ==> "+ item.first_name);
});
}
});

Read and Parse JSON data from POST request in C#

I'm doing a POST request via JQuery's Ajax, with the type of data defined as json, containing the values to be posted to server, something like Username: "Ali".
What I need to do in a Handler, is to read the values, deserialize them to an object named User.
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of data is the following:
Username=Ali&Age=2....
Now I'm sure this isn't JSON, so the next line would certainly produce an error:
"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read JSON data from POST request?
Client Side
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: {
Username: 'Ali',
Age: 2,
Email: 'test'
},
success: function (data) {
},
error: function (error) {
}
});
Convert your object to json string:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});
I am not sure why your datastring is encoded like an url (as it seems).
But this might solve the problem (altough i am not sure)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);
Use This In c# file... Will give you result you require...
string username=Request.Form["Username"].ToString();
Similarly For others...
I hope this will help you
Another Answer Or you can send data like this
$.ajax({
url: '../Ajax/Ajax_MasterManagement_Girdle.aspx',
data: "Age=5&id=2"
type: 'POST',
success: function (data) {
}
});
ANd get the answer like this in c#
string Age=Request.Form["Age"].ToString();

How to pass a JSON array in javascript to my codebehind file

I am getting a JSON object in my javascript function in aspx page. I need to fetch this data from my code behind file. How can I do it?
My javascript function is :
function codeAddress()
{
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
var requestParameter = '{' +
'output:"' + results + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: requestParameter,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() { alert("error"); }
});
});
}
Default.aspx.cs
[WebMethod]
public static string GetData( Object output)
{
return output.ToString();
}
I am getting the output as an array of objects instead of the actual result - [object Object],[object Object],[object Object] .Please provide me a solution to get the actual result. The JSON I am working on is given below
http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false
Create a WebMethod on your aspx Page that get the array on the page as:
[WebMethod]
public static GetData( type[] arr) // type could be "string myarr" or int type arrary - check this
{}
and make json request.
$.ajax({
type: 'POST',
url: 'Default.aspx/GetData',
data: "{'backerEntries':" + backerEntries.toString() + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {}
});
or you can use .post().
Check the url: in ajax request GetData WebMethod must be declared on the Default.aspx on that page where you are making ajax request.
Check this question to know that how to format array for sending to the web method.
Why doesn't jquery turn my array into a json string before sending to asp.net web method?
Check these links for reference:
Handling JSON Arrays returned from ASP.NET Web Services with jQuery - It is Best to take idea
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Categories

Resources