jQuery:在JSON中混合字符串和Javascript对象列表
我试图做的可能很简单,但是由于我对jQuery不太熟悉,我不知道如何做 我想将一些数据作为JSON发送到ASP.NET控制器。数据包含一些字符串和对象列表 代码看起来有点像这样: 视图: 控制器:jQuery:在JSON中混合字符串和Javascript对象列表,javascript,jquery,asp.net,json,controller,Javascript,Jquery,Asp.net,Json,Controller,我试图做的可能很简单,但是由于我对jQuery不太熟悉,我不知道如何做 我想将一些数据作为JSON发送到ASP.NET控制器。数据包含一些字符串和对象列表 代码看起来有点像这样: 视图: 控制器: public class Stuff { public int id { get; set; } public string option{ get; set; } } public void DoStuffWithStuff(stri
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
公共类的东西
{
公共int id{get;set;}
公共字符串选项{get;set;}
}
public void DoStuffWithStuff(字符串String1、String2、列表内容)
{
//做我的事
}
任何想法都很好!:) 不需要对json数据进行字符串化。 您只需创建一个要发送的对象,然后
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});
到目前为止看起来还不算太糟!只有几件事
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
您指定POST,因此必须使方法支持POST(在本例中,您也可以通过将类型更改为get,然后删除属性来避免get,但我不确定您的“东西”需要什么…)
您实际上没有将内容传递到您的方法中,这可能会有所帮助
下面是使用正确的JSON传递重新编写的ajax方法(用于您在这里尝试执行的操作)
非常感谢你!我不得不修改一些东西,但现在它就像一个符咒。我不得不删除contentType值,因为它由于某种原因破坏了一切,我需要删除dataRow中的JSON.stringify。现在一切都很好!没问题!谢谢你的留言,我会为其他人更新我的答案
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
$.ajax({
...
type: 'POST',
...
});
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});