Jquery 如何在mvc5中传递模型和字符串?
这是我的密码: JavaScript:Jquery 如何在mvc5中传递模型和字符串?,jquery,ajax,asp.net-mvc,c#-4.0,Jquery,Ajax,Asp.net Mvc,C# 4.0,这是我的密码: 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);
$(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代码控制器
public void PassThings(List<Thing> things,string name)
{
var t = things;
var namePass=name;
}
错误名称未定义。列表为空。请帮助我。您需要使用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 () {
....
}
});
列表将为空。ResOn:JSON是一种字符串类型,因此当您传递JSON对象时,它将是一个sting而不是List对象 在你的c代码中试试这个
public void PassThings(string things,string name)
{
//deserialzie the "things" using newtonsoft json convert then bind to List<> model
}
您不需要在Request中使用JSON.stringify和指定contentType。据我所知,序列化对象是区分大小写的。所以,id应该是你的东西的id和颜色[]var.@Bas,不,你错了,它不区分大小写。@MuhammadAzim,一切看起来都很好,只需删除'contentType:'application/json;charset=utf-8'`,它应该可以工作。还需要删除contentType:'application/json;字符集=utf-8'.@MokshShah,不,你没有。如果您这样做,这两个属性都将为null。我刚刚尝试了这种方法,但出现了一个错误,错误提示为无效的基元类型:things@MokshShah,我的答案中的代码是有效的-我只是使用OP的代码从我的项目中复制了它,并更改了我标记的行How?。。。它看起来很奇怪,对我来说,它说的是无效的JSON原语:东西,怎么可能?我可以给你看快照,告诉我应该在哪里发布?
public void PassThings(string things,string name)
{
//deserialzie the "things" using newtonsoft json convert then bind to List<> model
}