我想從ajax調用發送對象數組到控制器動作。從ajax獲取數據到mvc動作
在後端側我
容器類:
public class MyContainer
{
public string Id { get; set; }
public Filter[] Filters { get; set; }
}
public class Filter
{
public string Name { get; set; }
public string[] Values { get; set; }
}
和行動:
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
在前端側我
$(document).on('click', 'mySelector', function (event) {
//Create first object
var firstIds = {};
firstIds.Name = "Custom Name 1";
firstIds.Values = GetIds('param1'); //this return an array of strings
//Create second object
var secondIds = {};
secondIds.Name = "Custome Name 2";
secondIds.Values = GetIds('param2'); //another array
var Id = $(this).attr('id'); //id of element
//Add objects to array
var filters = [];
filters.push(firstIds);
filters.push(secondIds);
$.ajax({
method: "GET",
url: baseUrl+"/MyAction",
//traditional: true, //I tried with and without that parameter
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
});
所以如果我在例子中使用它頂部,運行中的容器對象具有Id值並且在過濾器中具有2個元素的數組,但是它們都具有Name和Values作爲null。
將傳統設置爲True,我得到了container.Id set但container.Filters = null。
有什麼建議嗎? 謝謝。