我正在尝试将javascript中的数组传回我的MVC应用程序。 javascript中有一个console.log(selected)
,它会输出一个数据数组:
["<img src="https://owlexpress.kennesaw.edu/stugifs/open.gif">", "MATH 1190/01 - Calculus I", "84528", " 4.000", "Full Term", "40", "34", "6", "0", "0", "0", "Kennesaw Campus", "Classroom - 100%", "Mathematics & StatisticsRoom 108", "8:00 am - 9:10 amLecture", "Aug 17, 2015", "Dec 14, 2015", "Xiaohui Rebecca Shi (P)", ""]
但是当控制器中的断点出现时,我会看到selectedClassesArray == null
使用Javascript:
$('#WatchButton').on('click', function (e) {
var selected = [];
$("tr.selected").each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
});
});
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: [selected],
traditional: true,
success: function (data) { alert("SUCCESS"); }
});
});
视图模型:
public class SelectedClassesArray
{
public string[] arrayOfClasses { get; set; }
}
控制器行动:
//Had to set ValidateInput to false since one of the strings contains < (it errored without this)
[HttpPost, ValidateInput(false)]
public ActionResult watchClasses(IEnumerable<SelectedClassesArray> selectedClassesArray)
{ //Breakpoint here shows that selectedClassesArray is null
foreach (var item in selectedClassesArray)
{
Console.WriteLine(item.ToString());
}
return View();
}
答案 0 :(得分:2)
您的操作需要一个数组列表:
watchClasses(IEnumerable<SelectedClassesArray> selectedClassesArray)
您可能只希望获得视图模型中的数组:
watchClasses(SelectedClassesArray selectedClassesArray)
@taxicala所说的有意义,尝试只传递数组,而不是另一个数组中的数组:
data: { selectedClassesArray: selected }
已发布的属性名称必须与视图模型参数的名称匹配。
答案 1 :(得分:0)
你有没有尝试过:
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: selected,
traditional: true,
success: function (data) { alert("SUCCESS"); }
});
或许传统的序列化失败了:
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: { selectedClassesArray: selected },
traditional: false,
success: function (data) { alert("SUCCESS"); }
});