*转载请注明出处:
作者:willingtolove;
本文链接:http://www.cnblogs.com/willingtolove/p/4741549.html
正文:
1. 方法一:利用ajax
1) 客户端js代码:
1 //获取对象数组 2 function GetQAS() { 3 var stuAnswerList = []; 4 var stuAnswer = { 'answerID': 1, 'answerType': 1, 'answerContent': 'one', 'answerSingle': 1, 'answerMultiple': '1,2', 'answerTOF': true }; 5 var stuAnswer1 = { 'answerID': 1, 'answerType': 1, 'answerContent': 'two', 'answerSingle': 1, 'answerMultiple': '1,2', 'answerTOF': true }; 6 7 stuAnswerList.push(stuAnswer); 8 stuAnswerList.push(stuAnswer);
return stuAnswerList; 9 } 10 //ajax提交数据 11 function SubmitStuAnswersAjax(stuAnswerArr) { 12 13 $.ajax({ 14 url: "../../Paper/SubmitStuAnswers", 15 type: "post", 16 data: { stuAnswerArr: stuAnswerArr }, 17 async: false, 18 cache: false, 19 error: function (XMLHttpRequest, textStatus, errorThrown) { 20 if (XMLHttpRequest.status == 1001) { 21 eval(XMLHttpRequest.ResponseText); 22 } else { 23 alert("GetPaper error"); 24 } 25 }, 26 success: function (data) { 27 alert(data); 28 } 29 }); 30 } 31 //按钮点击方法 32 function SubmitStuAnswersBtn() { 33 var stuAnswerArr = GetQAS(); 34 SubmitStuAnswersAjax(stuAnswerArr); 35 }
2) 服务端C#代码:
//stuAnswerEntity public class stuAnswerEntity { public int answerID { set; get; } public int answerType { set; get; } public int answerSingle { set; get; } public string answerMultiple { set; get; } public bool answerTOF { set; get; } public string answerContent { set; get; } } //stuAnswerArr 注意前后台变量名称一定要相同 public ActionResult SubmitStuAnswers(List<stuAnswerEntity> stuAnswerArr) { bool re = false; List<stuAnswerEntity> stuAnswerEntityList = new List<stuAnswerEntity>(); stuAnswerEntityList = stuAnswerArr; //此时stuAnswerArr中就存有前台stuAnswerArr中的数据; return Content(re.ToString()); }
2. 方法二:js模拟form 进行post提交
1) 客户端js代码:
1 function REV_SubmitStuAnswersBtn() { 2 var stuAnswerArr=JSON.stringify(GetQAS());//转成json字符串 3 //JS模拟post提交 4 var REVQForm = document.createElement("form"); 5 REVQForm.setAttribute("method", 'POST'); 6 REVQForm.setAttribute("action", '../Paper/GetREVPaper'); 7 REVQForm.innerHTML = ""; 8 var stuAnswerInput = document.createElement("input"); 9 stuAnswerInput.setAttribute("type", "hidden"); 10 stuAnswerInput.setAttribute("name", 'REVQ');//'REVQ' 11 stuAnswerInput.setAttribute("value", stuAnswerArr); 12 REVQForm.appendChild(stuAnswerInput); 13 14 document.body.appendChild(REVQForm); 15 REVQForm.submit(); 16 }
2) 服务端C#代码:以json字符串的方式传输
public ActionResult GetREVPaper() { bool re = false; string stuAnswerJson = Request["REVQ"] == null ? "" : Request["REVQ"];//'REVQ' //将json字符串反序列化 List<stuAnswerEntity> studentAnswerList = JsonConvert.DeserializeObject<List<stuAnswerEntity>>(stuAnswerJson); return Content(re.ToString()); }
作者: | willingtolove |
本文链接: | js 提交对象数组到服务端的方法总结 |
欢迎经常来转转,转载请注明出处! |