var id="@ViewBag.ID"; var userList = []; userList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-04"}); userList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-05"}); userList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-06"}); userList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-07" }); var idList = []; idList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-04" }); idList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-05" }); idList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-06" }); idList.push({ _strOptionalID: 1, _dtStartDate: "2017-05-01", _dtEndDate: "2017-05-07" }); $.ajax({ url: '/Home/Index', type: 'post', contentType: 'application/json', data: {ID:id, UserList : JSON.stringify(userList ), IDList: JSON.stringify(idList)}, async:true, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("数据错误!"); }, success: function (data) { if (data) alert("保存成功!"); else (data) alert("保存失败,请联系管理员!"); } });
1 data: JSON.stringify({ID:id, UserList :userList , IDList: idList}),
1 string myjson = string.Empty; 2 using (StreamReader sr = new StreamReader(Request.InputStream)) 3 { 4 myjson = sr.ReadToEnd(); 5 } 6 System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 7 test test = serializer.Deserialize<test>(myjson); 8 9 10 public class Users 11 { 12 public int _strOptionalID { get; set; } 13 public DateTime _dtStartDate { get; set; } 14 public DateTime _dtEndDate { get; set; } 15 } 16 17 public class test 18 { 19 public int id { get; set; } 20 21 public List<Users> userList { get; set; } 22 }
public jsonResult Index(string ID,string UserList,string IDList){ //拿到值后 进行json反序列划就行了 }
哎,可是我现在就是拿不到值
@你猜丶: 你用浏览器看下 发出请求的时候 带了哪些参数
@DNLi: 哦哦,拿到了,而且反序列化出来了,但是有个问题,空值无法去掉,哎
@你猜丶: 空值?在服务端拿到null值?截图瞧瞧呗
@DNLi:
string lists=“ [{ "UserName": "姓名", "UserPassWord": "密码"},{},{} }”;
就是这样的里面有{}号,之后反序列化
List<Data> plists=Newtonsoft.Json.JsonConvert.DeserializeObject<List<Data>>(lists);
这句会得到三条,我只要第一条就行了,那个空的不要
@你猜丶: 序列化实体有问题 你客户端传过去 拿到的字符串 发出来
@DNLi:
var lists = [];
$("#Div").children("div").each(function (i) {
lists.push({
UserName: $("#UserName" + i).val(),
UserPassWord: $("#UserPassWord" + i).val(),
});
})
我是原本就是遍历获取到的值,所以前台获取数据没错
@你猜丶:
public class userModel{ public string UserName{get;set;} public string UserPassWord{get;set;} } list<userModel> list_UserModel= JsonConvert.DeserializeObject<list<userModel>>(lists);
@DNLi: 嗯啊,我就是这样做的吗,但是现在是前台接收的时候会有好几个{},然后反序列化后也有
@你猜丶: 那就是前台那边的问题了