Process json object in spring controller - javascript

I have this basic quiz app that I'm trying to build and right now I'm stuck on processing the submitted quiz answers in spring.
I use a js function to store the question id and submitted answers id's in a json object like so:
{
1: [2,3,4],
2: [1,2]
}
So, the user sent the answers 2,3,4 for the question with the id of 1. Now, I'm trying to send this json object to the spring controller method using ajax.
// DO POST
function ajaxSubmitAns(formdata){
$.ajax({
type : "POST",
url : "/process-answers",
data: JSON.stringify(formData),
contentType : 'application/json; charset=utf-8',
dataType: 'json',
headers: {
Accept: 'application/json'
},
success: function(){
//do something
},
error : function(e) {
//error
}
});
}
I also wrote the controller function but what I don't know is how do I access these values from the json object. How can I loop through the keys (questions id's) and get the values?
What I have for the controller is this so far:
#RequestMapping(value = "/process-answers", method = RequestMethod.GET)
#SuppressWarnings("unchecked")
public #ResponseBody
String processQuizz(#RequestBody String json) {
}

#PostMapping("/process-answers")
#ResponseBody
public void processQuizz(#RequestBody Map<Integer, List<Integer> quiz) {
quiz.forEach((quizId, answers) -> ... your business logic here ...);
}
Now you can iterate through your map directly without json processing.

Related

Get data from ajax to mvc action

I want to send array of objects from ajax call to controller action.
On back-end side I have
container classes:
public class MyContainer
{
public string Id { get; set; }
public Filter[] Filters { get; set; }
}
public class Filter
{
public string Name { get; set; }
public string[] Values { get; set; }
}
and action:
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
On front-end side I have
$(document).on('click', 'mySelector', function (event) {
//Create first object
var firstIds = {};
firstIds.Name = "Custom Name 1";
firstIds.Values = GetIds('param1'); //this return an array of strings
//Create second object
var secondIds = {};
secondIds.Name = "Custome Name 2";
secondIds.Values = GetIds('param2'); //another array
var Id = $(this).attr('id'); //id of element
//Add objects to array
var filters = [];
filters.push(firstIds);
filters.push(secondIds);
$.ajax({
method: "GET",
url: baseUrl+"/MyAction",
//traditional: true, //I tried with and without that parameter
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
});
So if I use it like in example on top, container-object in action have Id value and have array of 2 elements in Filters, however both of them have Name and Values as null.
With traditional set to True, I got container.Id set but container.Filters = null.
Any suggestion?
Thank you.
Use a POST request in combination with JSON.stringify() method.
C#
[HttpPost]
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
JQUERY
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:JSON.stringify(
{
Id: Id,
Filters: filters
}),
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Why do you need JSON.stringify() method ?
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
You should use POST method instead of GET in ajax request. As you are posting data. and also your action should have [HttpPost] decorator.
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Though its an old post, adding my bit to it. I would ask if you are returning a view from the action or not? here it seems like you are not returning a view but just wanting to update some data.
But in case you wanted to return a view, for e.g like showing some product info, then you would just pass the selected product's id to the action method, retrieve the related product information and then pass on this data as a model to the view, and then return the complete view. In this case you don't need a separate ajax call to process the data, instead just do it when you are requesting for the view itself (through the action method).
On the contrary if you already have the view rendered and are just wanting to change the data inside the current view then just resort to an ajax call to get the data without any view.
Hope it helps

MVC5 Controller not receiving JSON Object

I have a controller with method as follows:
public JsonResult Save(List<BlogInfo> list)
{
return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}
And I have an ajax post from the client as follows:
$.ajax({
url: "Home/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(ViewModel),
success: function (response) {
alert(response.Status);
}
});
My problem is that list parameter to the controller is always null. I tried changing it to string instead of List but that is also null.
Using Fiddler, I can see that the JSON is being pass as follows:
{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}
The JSON you have shown doesn't represent an array, so you cannot possibly expect to bind it to a list on the server. To achieve that make sure that you are sending an array of objects from the client:
data: ko.mapping.toJSON(ViewModel.Data);
Here we take the ViewModel.Data property which represents an array so that we send only the desired JSON:
[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":‌​"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description‌​","Tags":[]}]

How to pass object array containing both data and file through ajax and retrieve in mvc controller? [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I have an object array like the following.
var array=[
{
Name:"name",
Address:"address",
Files://array of files
},
{
Name:"name",
Address:"address",
Files://array of files
}
];
I need to pass the array through ajax and retrieve it on mvc controller. I am not getting both data and file at the same time as array in controller.
I have used formData in case of single object.But in the case of array I don't know how.Anyone please help
my code..
model..
public class DataModel{
public string Name{get;set;},
public string Address{get;set;},
public HttpPostedFileBase[] Files{get;set;}
}
Controller..
[HttpPost]
public JsonResult AddData(List<DataModel> data)
{
//code
}
ajax//
$.ajax({
type: "POST",
url: '/Mydata/AddData',
data: {data:array},
contentType: false,
processData: false,
dataType: "json",
success: function (json) {
//some function
}
});
You can pass array by stringifying the array and pass it through data attribute of ajax.
var _myArray=JSON.stringify(array),
$.ajax({
//Rest of the code
data: _myArray,
});

Sending a LIST of JSON object from javascript to MVC action

In my javascript i make a JSON like object with two properties : ControllerName and WordNumber and add them to an Array.
function TestN() {
var list = new Array();
$("*[wordNum]").each(function ()
{
var endRes = {
ControllerName: this.id,
WordNumber: this.getAttribute("wordNum")
};
list.push(endRes);
});
jQuery.ajax({
url:' #Url.Action("Translate")' ,
contentType: "application/json",
dataType: "json",
data: { List : JSON.stringify(list) }
,
traditional: true
})
}
</script>
In .net I've got this class with the same properties :
public class TranslateModel
{
public string ControllerName { get; set; }
public string WordNumber { get; set; }
}
And here is my action+
public ActionResult Translate(ICollection<TranslateModel> List)
{ return View(); }
As you may suppose the List property in Translate Action is empty (model binding doesn't work);
when you used JSON.stringify(list), it send string value to the controller action, instead of the object.
there are two approaches
1) either you send string to controller's action and Deserialize string to object and use.
2) create the model property as array of list and send that model to controller action without using JSON.stringify.
here are two links that may help you.
--approach-1
ASP.NET MVC 4 JSON Binding to the View Model - Nested object error
--approach-2
Passing json list to MVC 3
Try changing your AJAX function to this:
jQuery.ajax({
url: ' #Url.Action("Translate")',
type: 'POST',
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ 'List': list }),
traditional: true
});

string[] via Ajax and ASP.Net (MVC)

my problem is following.
I try to parse some data via ajax, passing the data to my controller:
AJAX
$.ajax({
type: "GET",
url: "ParseOrganizaitonPath",
data: {
organizationPath: $('#organizationPath').val()
},
success:
function (data) {
//data is from type string with value "System.string[]"
//but should be from type System.string[]
});
}
});
Controller
public string[] ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return organizations.ToArray();
}
I am reaching the controller method and in it everything is fine, but the data that is comming back (ajax part, success method) is just a string ("System.string[]", data[0] S, data[1]y data[2]s...) but not the data I want. (For example if i pass the input "test/one" I want to have as result data[0] test, data[1] one)
Hope you understand what my Problem is.
Thanks in advance!
Julian
Have to tried to use the JavaScriptSerializer? Have a look at this example:
public string ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
return oSerializer.Serialize(organizations);
}
To deserialize the JSON string with JavaScript you can use the parse function:
var array = JSON.parse(data);
I found a way where you don't have to serialize it (on c# site) and parse it (on javascript site)
Just use the JSON Method that is inherited from the Controller and return an JsonResult:
public JsonResult ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return JSON(organizations);
}
On the client site (javascript) you have to use JSON.stringfy(dataObject) for data that you want to send to your controller-method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ParseOrganizaitonPath",
data: JSON.stringify(myDataObject),
success:
function (data) {
//use your data
});
}
});
That's how it worked for me.
Good luck!
Julian

Categories