user6934713 user6934713 - 22 days ago 7
AngularJS Question

Pass javascript object with http post

I am trying to pass a javascript object that contains

question(string), multianswers(answer(string),correct(bit)).


This is the value of multianswers -

[{'correct':true,'answer':'A1'}, {'correct':true,'answer':'A2'}];


What type should be the parameter that I am passing to the controller.

function setMultiQuestion(question, responses) {

var responsesList = angular.toJson(responses);

function questionAnswerObj(question, answers)
{
this.question = question;
this.answers = answers;
}

qaObject = new questionAnswerObj(question, responsesList);

$http.post(baseUrl + "Admin/insertMultiAnswers", { data: qaObject })
.success(function (data, status, headers, config) {

$mdDialog.hide();
$mdToast.show(
$mdToast.simple()
.textContent('New question was added.')
.position('top')
.hideDelay(5000)
.theme('success-toast')
);
})
.error(function (data, status, header, config) {
});
}


And this is my controller.

[HttpPost]
public ActionResult insertMultiAnswers(object data)
{
try
{
Console.Write(data);
// data.setMultiAnswer();
Response.StatusCode = 200;
return Content("Sucess");
}
catch (Exception ex)
{
Response.StatusCode = 500;
return Content("Fail");
}
}

Answer

What type should be the parameter that I am passing to the controller.

string[] data

This is due to the [{'correct':true,'answer':'A1'}, {'correct':true,'answer':'A2'}];. Brackets mean array. {} mean object. So your array consists out of objects containing values.

To further manipulate the array in the controller, I would suggest looking at these examples. http://sarangasl.blogspot.nl/2014/01/pass-complex-javascript-object-to-mvc.html

You could for example create a class containing a bool correct and string answer, and cast the objects in the array in the controller to this class. This makes it easy to use them later on. Example of a plugin which simplifies this process is deserializing JSON to .net object using NewtonSoft (or linq to json maybe?)