【发布时间】:2016-02-08 22:06:15
【问题描述】:
我的 Jquery 代码创建了三个对象,然后将它们放在另一个对象中,该对象使用 JSON.stringify 发布到控制器中的操作。
动作中的字符串如下所示:
{"sources":{"0":{"Name":"aaaaa","IP":"1.1.1.1","Username":"vvvv"},"1":{"Name":"bbbb","IP":"2.2.2.2","Username":"fdfdfdf"}},"destinations":{"0":{"Name":"aaaaa","IP":"1.1.1.1"},"1":{"Name":"bbbb","IP":"2.2.2.2"}},"protocols":{"0":{"Name":"dsfsdfsdf","Type":"FTP,SSH","Port":"22,33"}},"remarks":"sdfsdfsdf"}
所以这三个对象是:
var sources = {};
var destinations = {};
var protocols = {};
充满:
sources[iS] = { 'Name': field1, 'IP': field2, 'Username': field3 };
(iS 是一个计数器)
destinations[iD] = { 'Name': field1, 'IP': field2 };
(iD 是一个计数器)
protocols[iP] = { 'Name': field1, 'Type': field2, 'Port': field3 }
(iP 是一个计数器)
它们被放在一起:
var remarks = $('#txtRemarks').val();
var postdata = { "sources": sources, "destinations": destinations, "protocols": protocols, "remarks": remarks };
然后发布:
$.ajax({
url: ThisController + '/AddRule',
type: 'POST',
data: 'postdata='+JSON.stringify(postdata),
dataType: 'json',
traditional: true,
success: function (data) {
$('#pnDataCollection').html(data);
});
并收到:
[HttpPost]
public ActionResult AddRule(string postdata)
{
return HttpNotFound();
}
我有三个班级:
public class Source
{
public string Name { get; set; }
public string IP { get; set; }
public string UserName { get; set; }
}
public class Destination
{
public string Name { get; set; }
public string IP { get; set; }
}
public class Protocol
{
public string Name { get; set; }
public string Type { get; set; }
public string Port { get; set; }
}
我怎样才能将 JSON 字符串中的三个对象变为:
List<Source> = DoSomeThingWith(JsonString for Sources)
List<Destination> = DoSomeThingWith(JsonString for Destinations)
List<Protocol> = DoSomeThingWith(JsonString for Protocols)
??
【问题讨论】:
-
您的代码中没有数组,只有对象!
-
谢谢,更新了问题。
-
显示您发布到的方法的签名。如果您想绑定到
IEnumerable<Source>,那么您确实需要一个数组 -[{"Name":"aaaaa","IP":"1.1.1.1" ...}, {"Name":"bbbb","IP":"2.2.2.2"}]等 -
我已经添加了方法。还不算多。
-
现在没时间,但我会在大约 45 分钟后添加答案
标签: jquery arrays json asp.net-mvc