2016-04-21 116 views
0

試圖從我的jQuery腳本中將對象列表傳遞給我的MVC控制器。控制器沒有得到名單。有任何想法嗎?通過jQuery將數組傳遞給MVC控制器

腳本

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

控制器

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

模型

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

首先,我會嘗試數據:json.stringify(模型)在ajax,有時幫助。接下來我會仔細看看日期。我懷疑你可以將JavaScript日期映射到C#DateTime對象上。我可能會創建該對象與它的日期部分(月,日,年,每個作爲單獨的值),然後根據這些值在控制器中創建DateTime對象。 – nurdyguy

+1

如果您將列表作爲已經序列化的字符串發送,則MVC模型綁定器可能將其解釋爲「字符串」而不是「List」。在將其添加到模型之前,請嘗試列表字符串上的'json_decode'。 – jmoerdyk

+0

添加'contentType:「application/json; charset = utf-8」,'並將其更改爲'data:JSON.stringify(model)' –

回答

0

替換此線

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

與此

var model = { planId: planId, date: date, list: JSON.parse(list) }; 
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 
     }, 
    }); 
} 

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()。

相關問題