Passing array to MVC controller via jQuery

时间:2016-04-21 21:59:54

标签: jquery asp.net-mvc

Trying to pass a list of objects to my MVC controller from my jquery script. The controller ain't getting the list. Any ideas?

Script

function refreshXeroData(obj, planId, date, list) {
    // list comes in as a serialized array
    // list = "[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":""},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]"

    var model = { PlanId: planId, Date: date, List: list };

    $.ajax({
        type: 'POST',
        url: url,
        data: model,
        success: function (data) {
            // code removed for clarity
        },
     });
 }

Controller

public JsonResult Refresh(int planId, DateTime date, List<XeroScenarioModel> list)
{
    // list is null
    // code removed for clarity
}

Model

public class XeroScenarioModel
{
    public int Id { get; set; }
    public string XeroFromDate { get; set; }
    public string XeroToDate { get; set; }
}

2 个答案:

答案 0 :(得分:0)

我仔细检查了下面提到的代码。

<script type="text/javascript">
function refreshXeroData() {
    // list comes in as a serialized array
    var planId = 1234;
    var date = new Date();
    list = '[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]';

    var model = { planId: planId, date: "4/30/2016 12:00:00 AM", list: JSON.parse(list) };

    $.ajax({
        type: 'POST',
        url: '../../Sample/Refresh',
        data: JSON.stringify(model),
        contentType: "application/json",
        success: function (data) {
            // code removed for clarity
        },
     });
}

答案 1 :(得分:0)

我在传入的数组上使用了JSON.parse()。

// list = "[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":""},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]"
var model = { PlanId: planId, Date: date, List: JSON.parse(list) };

$.ajax({
   type: 'POST',
   url: url,
   data: model,
   success: function (data) {
       // code removed for clarity
   },
});

不需要JSON.stringify()。