[英]Angular - Pass array with http post
I am trying to pass a json array and a value with http post. 我试图通过json传递一个json数组和一个值。 The value was passed but the array not.
该值已传递,但数组未传递。 The value of responsesList in the javascript controller is : "[{"correct":"false","answer":"a1"},{"correct":true,"answer":"a2"}]"
在javascript控制器中,responseList的值是:“ [{{correct”:“ false”,“ answer”:“ a1”},{“ correct”:true,“ answer”:“ a2”}]“”
javascript controller JavaScript控制器
function setMultiQuestion(question, responses)
{
var jsonData = angular.toJson(responses);
var responsesList = {'object':jsonData};;
$http.post(baseUrl + "Admin/insertMultiAnswers", { question: question, responsesList: responsesList })
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
}
MVC Controller MVC控制器
[HttpPost]
public ActionResult insertMultiAnswers(MultiChoiceQuestionModel model)
{
try
{
model.setMultiAnswer();
Response.StatusCode = 200;
return Content("Sucess");
}
catch (Exception ex)
{
Response.StatusCode = 500;
return Content("Fail");
}
}
MODEL 模型
public class answerObj
{
public bool correct { get; set; }
public string answer { get; set; }
}
public class MultiChoiceQuestionModel
{
public string question { get; set; }
public List<answerObj> responsesList = new List<answerObj>();
public void setMultiAnswer()
{
using (ATLASEntities atlasEntity = new ATLASEntities())
{
Console.Write(responsesList.Count);
}
}
angular.toJson(responses)
serializes to string not to an object. 序列化为字符串而不是对象。 You should just do
你应该做
responsesList: responses
In order to be mapped to a list the object from the json needs to be an array. 为了映射到列表,来自json的对象必须是一个数组。
So, if you change below 因此,如果您在下面进行更改
var responsesList = {'object':jsonData};;
to something like: 像这样:
var responsesList = [{'correct':true,'answer':'Meow'}, {'correct':true,'answer':'Woof'}];
It will work. 它会工作。
I assume that you get plain array ( []
) from responses
and not array that is inside of string value ( "[]"
). 我假设您从
responses
获得普通数组( []
),而不是字符串值( "[]"
)内的数组。 Try this: 尝试这个:
function setMultiQuestion(question, responses){
var myObj = {};
myObj = JSON.stringify({question: question, responsesList: responses});
$http.post(baseUrl + "Admin/insertMultiAnswers", myObj)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
}
You might have to parse that string in your backend. 您可能必须在后端解析该字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.