这是我的代码:
JavaScript的:
$(document).ready(function () {
//Thing is model
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify( things);
var name="test";
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: {
things:things,
name:name
},
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
C#: 这是我的C#code.Controller。
public void PassThings(List<Thing> things,string name)
{
var t = things;
var namePass=name;
}
//模型
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
错误名称未定义。列表为null.please帮助我。
答案 0 :(得分:1)
您需要使用ajax traditional: true
选项并修改字符串化数据的方式。删除
things = JSON.stringify( things);
并将ajax调整为
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '@Url.Action("PassThings", "Home")', // recommended best practice
traditional: true, // add this
data: JSON.stringify({ things: things, name:name }), // modify this
success: function () {
....
}
});
答案 1 :(得分:-1)
列表将为null。 Resaon:JSON是一种字符串,所以当你传递json对象things
时,它将是一个sting而不是List&lt;&gt;宾语。
在你的c#代码中试试这个
public void PassThings(string things,string name)
{
//deserialzie the "things" using newtonsoft json convert then bind to List<> model
}