Passing an array of integers from JavaScript to a controller action of List<int>

淺唱寂寞╮ 提交于 2019-12-11 22:54:18

问题


I am using javascript code to postdata to a controller action coded in C#. I am getting a null value when attempting to pass an array of integers in javascript created as follows:

var answers = [];
answers.push(1);
answers.push(2);
answers.push(3);

I can see from javascript alert that the values are going into array as when I try answers.tostring I am getting the value "1,2,3" as expected, I am then trying the following postdata

var postData = {
                'surveyID': surveyID,
                'questionID': questionID,
                'answers': answers,
                'answerText': null,
                'comment': comment,
                'questionType': questionType
            };

This is targetting the following controller action but the array of integers does not seem to be carrying across to the controller action as my List is always null

[HttpPost]
public PartialViewResult GoForward(int surveyID, int questionID, List<int> answers, string answerText, string comment, string questionType)
{}

Any know how I can get the postdata array to translate to a List that is not null?


回答1:


Because MVC expects the data in QueryString pattern like this:
answers=1&answers=2&answers=3

If you use jQuery to do AJAX, default is
answers[]=1&answers[]=2&answers[]=3

You could try traditional option

$.ajax({
  //...
  traditional:true,
  //...
});

refer to https://api.jquery.com/jQuery.ajax/



来源:https://stackoverflow.com/questions/23232639/passing-an-array-of-integers-from-javascript-to-a-controller-action-of-listint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!