jQuery: Mixing Strings and List of Javascript Objects in JSON - javascript

What I'm trying to do is possibly quite simple, however beeing not very familiar with jQuery I can't figure out how to do it.
I want to send some Data as JSON to an ASP.NET Controller. The Data contains some Strings and a list of Objects.
The Code would look somewhat like this:
View:
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Controller:
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
Any Ideas would be great! :)

You do not need to stringify the json data.
You just create an object you van to send and than
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});

It actually doesn't look too bad so far! Just a few things...
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
In here, you don't actually give a type to string2. I'm going to assume this is a typo, but that's the minor part here.
Also, in that method, notice it has the HttpPost on the top. In your javascript here:
$.ajax({
...
type: 'POST',
...
});
You specify POST, so you must make the method support post (You could also get away with GET in this case by changing type to GET, then removing the attribute, but i'm not sure what your "stuff" entails...)
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
You didn't actually pass stuff into your method, which may be helpful...
Here is the ajax method re-written with the proper JSON pass (for what you're trying to do here).
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});

Related

Sending Array Object Data in Javascript to ASP.NET Core Controller using AJAX ()

I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!

Cannot figure out why I pass an array of JavaScript objects to controller method that the controller method isn't getting the object

I been looking around for awhile now and have came across this question many times and I am doing the same thing that are in the solutions but baffled why its not working.
I'm sure this question will be marked as a duplicate, and it is, but I am missing something.
Here is the array of JavaScript objects
var gridData = {
tempData: [
{ UserName: "Tom", LastName: "Solomon" },
{ UserName: "Harry", LastName: "Solomon" },
{ UserName: "Sally", LastName: "Solomon" },
{ UserName: "Dick", LastName: "Solomon" },
]
};
Here is my Ajax
function TossIt() {
var sendThis = gridData.tempData;
console.log(sendThis);
$.ajax({
type: "POST",
url: "/Junk/JAT?s=" + sendThis,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendThis),
success: function (data, textStatus, jqXHR) { },
complete: function (e) {
}
})
}
Here is the method I am passing it to
[HttpPost]
public List<Stuff> JAT(Stuff s)
{
List<Stuff> result = new List<Stuff>();
return result;
}
and here is the class
public class Stuff
{
public string UserName { get; set; }
public string LastName { get; set; }
}
I have a break point on the JAT method and s is always null
EDIT
I need to manipulate some of the properties in objects then return the list
There are a number of issues with your code
You cannot send a javascript array of objects in a query string
parameter and your url needs to be just url: '/Junk/JAT',, or
preferably url: #Url.Action("JAT", "Junk"); which will ensure the
url is correctly generated (as a side note, to bind the model from a
query string, it would need to be
/Junk/JAT?[0].UserName=Tom&[0].LastName=Solomon&[1].UserName=Harry&.....)
Your sending an array of objects representing a Stuff, therefore
the parameter in the POST method must also implement
IEnumerable<Stuff> (not a single Stuff)
Your specifying that the method return json (your use of dataType: "json",) so therefore the method must return a JsonResult.
You code should be
Script
$.ajax({
type: "POST",
url: '#Url.Action("JAT", "Junk")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ s: sendThis }),
success: function (data, textStatus, jqXHR) {
.... // do something with the data you return
},
complete: function (e) {
}
})
Controller
[HttpPost]
public JsonResult JAT(List<Stuff> s) // or ActionResult
{
.... // manipulate the collection as required
return Json(s);
}
[HttpPost]
public List<Stuff> JAT([FromBody]List<Stuff> s)
{
List<Stuff> result = new List<Stuff>();
return result;
}
The answer above using POST is the way to go. However, if you want to do GET and queryStrings, you can as well.
Trivial example:
Client side (see $.param())
var gridData = {
tempData: [
{ UserName: "Tom", LastName: "Solomon" },
{ UserName: "Harry", LastName: "Solomon" },
{ UserName: "Sally", LastName: "Solomon" },
{ UserName: "Dick", LastName: "Solomon" },
]
};
function TossIt() {
var sendThis = gridData.tempData;
console.log(sendThis);
$.ajax({
type: "GET",
url: "/JAT?" + $.param(gridData), //using $.param() here for query string
success: function(data, textStatus, jqXHR) {},
complete: function(e) {
}
});
}
Controller side
follow the above comments/answer regarding List<Stuff>
HttpGet Attribute
Adjust the parameter name to tempData (re: $.param())
[System.Web.Mvc.HttpGet]
public List<Stuff> JAT(List<Stuff> tempData)
{
......
}
Hth...

Add parameter in Ajax call if a conditions is true

Here is my previous code:
$.ajax({
type: "POST",
url: "/Test/Save",
data: {
comments: $('#comments').val()
<% if (SomeCondition) { %>,
profit: parseInt(profitCombo.getSelectedValue())
<% } %>,
myData: JSON.stringify(someData).toString()
}
...
Now, I placed this code in a separate JS file and I need to remove the ASPX call. I have a variable someConditionJsVariable, so I want to make something like this:
data: {
comments: $('#comments').val()
if (someConditionJsVariable) {,
profit: parseInt(profitCombo.getSelectedValue())
},
myData: JSON.stringify(someData).toString()
}
If that variable is true, add a comma and another parameter. how to make this?
You can update code to following
// create object
var data = {
comments: $('#comments').val(),
myData: JSON.stringify(someData).toString()
}
if (someConditionJsVariable) {,
data.profit = parseInt(profitCombo.getSelectedValue());
}
data : data // pass object
Just build your object before, using a function:
$.ajax({
type: "POST",
url: "/Test/Save",
data: getMyDataObject()
//other settings
});
function getMyDataObject() {
var myDataObject = {
comments: $('#comments').val()
myData: JSON.stringify(someData).toString()
}
if (someConditionJsVariable) {
myDataObject.profit= parseInt(profitCombo.getSelectedValue());
}
return myDataObject;
}
You could wrap all of the logic into a function like so:
var testSave = function(someConditionJsVariable, someData, profitCombo) {
// construct your data object
var data = {
comments: $('#comments').val(),
myData: JSON.stringify(someData),
}
// assign the conditional property with value depending on condition
!!someConditionJsVariable && (data.profit = parseInt(profitCombo.getSelectedValue()));
// return the jQuery promise from ajax call
return $.ajax({
type: "POST",
url: "/Test/Save",
data: data
});
}
And then use the function like this:
testSave(someConditionJsVariable, someData, profitCombo)
.then(function(result) {
// do something with result
});

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

MVC JsonResult not working with chrome?

i want jquery to take a JsonResult from my MVC controller but it does'nt receive any data!
If I put the output into a textfile and enter its link its working so I think my jQuery is fine.
Then I was testing with other browsers like chrome and I saw NOTHING. The requested page was just emtpy.. no errors. Also IE seems to have problems receiving my string.. only firefox displays the string but why?
public JsonResult jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
}
r.Close();
return Json(requests);
}
I found out that also if I want to return the JSON as string its not working!
Its working with a string in all browsers now.. but jQuery is still not loading anything
var url = "http://../jsonLastRequests";
var source =
{
datatype: "json",
datafields: [
{ name: 'ID' },
{ name: 'SiteID' },
{ name: 'Lat' },
{ name: 'CreationTime' },
{ name: 'City' },
],
id: 'id',
url: url
};
var dataAdapter = new $.jqx.dataAdapter(source, {
downloadComplete: function (data, status, xhr) { },
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
I fixed my problem by adding:
access-control-allow-origin:*
public HtmlString jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
} r.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return new HtmlString(jSerializer.Serialize(requests ));}
I have done same approch like this
$.ajax({
type: 'POST',
url: '/home/GetSurvey',
data: {
XmlPath: $("#xmlpath").val()
},
dataType: 'json',
success: function (jsonData) {
jsonStringQuestionaire = jsonData;
LoadSurvey();
},
error: function () {
alert('Error loading ' + id);
}
});
questionaireJsonList = eval(jsonStringQuestionaire);

Categories

Resources