传递整数数组从JavaScript列出℃的控制器动作; INT> [英] Passing an array of integers from JavaScript to a controller action of List<int>

查看:102
本文介绍了传递整数数组从JavaScript列出℃的控制器动作; INT>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javascript code到POSTDATA在C#中的控制器操作codeD。我正在试图通过建立在JavaScript整数数组时,一个空值如下:

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);

我可以从JavaScript警告看到,值进入阵列,当我尝试answers.tostring我得到的值1,2,3果然,我则尝试以下POSTDATA

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)
{}

任何知道我怎么能得到POSTDATA数组转换为一个列表,不为空?

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

推荐答案

由于MVC预计这样的查询字符串模式中的数据:结果
答案= 1和;答案= 2及答案= 3

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

如果您使用jQuery做AJAX,默认结果
答案[] = 1和;答案[] = 2及答案[] = 3

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

您可以尝试传统的选项

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

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

这篇关于传递整数数组从JavaScript列出℃的控制器动作; INT&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆