JS提交对象数组到服务端的方法总结(C#实例)

*转载请注明出处:

作者:willingtolove;

本文链接:http://www.cnblogs.com/willingtolove/p/4741549.html

正文:

1. 方法一:利用ajax

  1) 客户端js代码:

 //获取对象数组
function GetQAS() {
var stuAnswerList = [];
var stuAnswer = { 'answerID': 1, 'answerType': 1, 'answerContent': 'one', 'answerSingle': 1, 'answerMultiple': '1,2', 'answerTOF': true };
var stuAnswer1 = { 'answerID': 1, 'answerType': 1, 'answerContent': 'two', 'answerSingle': 1, 'answerMultiple': '1,2', 'answerTOF': true }; stuAnswerList.push(stuAnswer);
stuAnswerList.push(stuAnswer);
    return stuAnswerList;
}
//ajax提交数据
function SubmitStuAnswersAjax(stuAnswerArr) { $.ajax({
url: "../../Paper/SubmitStuAnswers",
type: "post",
data: { stuAnswerArr: stuAnswerArr },
async: false,
cache: false,
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 1001) {
eval(XMLHttpRequest.ResponseText);
} else {
alert("GetPaper error");
}
},
success: function (data) {
alert(data);
}
});
}
//按钮点击方法
function SubmitStuAnswersBtn() {
var stuAnswerArr = GetQAS();
SubmitStuAnswersAjax(stuAnswerArr);
}

  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代码:

 function REV_SubmitStuAnswersBtn() {
var stuAnswerArr=JSON.stringify(GetQAS());//转成json字符串
//JS模拟post提交
var REVQForm = document.createElement("form");
REVQForm.setAttribute("method", 'POST');
REVQForm.setAttribute("action", '../Paper/GetREVPaper');
REVQForm.innerHTML = "";
var stuAnswerInput = document.createElement("input");
stuAnswerInput.setAttribute("type", "hidden");
stuAnswerInput.setAttribute("name", 'REVQ');//'REVQ'
stuAnswerInput.setAttribute("value", stuAnswerArr);
REVQForm.appendChild(stuAnswerInput); document.body.appendChild(REVQForm);
REVQForm.submit();
}

  

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 提交对象数组到服务端的方法总结
欢迎经常来转转,转载请注明出处!
上一篇:[转]解读Unity中的CG编写Shader系列二


下一篇:【MongoDB】NoSQL Manager for MongoDB 教程(基础篇)