json格式是web常用的数据传输类型,在WCF,MVC 都会用到。
1 服务器向客户端发送数据
return Json(resultMesage, JsonRequestBehavior.AllowGet); //resultMesage以json格式形式发送到页面
页面接收处理:
$.post("/student/question/addsamequestion",{id:id},function(data){
if(data.length> 0){ //按resultMesage类型处理
$(pthis).find("span").eq(0).html(data);
}
else{
$(pthis).attr("onclick",attr);
}
});
2 页面发送到服务器示例
var dataT="[ID:'@Model.ID', AverageScore: '@Model.AverageScore', ScoreNum:'@Model.ScoreNum', Score:score, ResultID:'@Model.ResultID', GuidedPlanID: '@Model.GuidedPlanID']";
$.ajax({
url: "/Teacher/PlanResult/ResultScore",
type: "POST",
data: {doWorkResults:dataT},
dataType: "Json",
async: false,
success: function (data) {
if(data <= 0)
dlg.Msg.Inf("您已评过分!");
else
{
dlg.Msg.Cor("评分成功!");
var num = parseInt($("#ScoreNum").text())+1;
$("#ScoreNum").text(num);
$("#AverageScore").text(data);
}
}
});
服务器接收处理
[HttpPost]
public JsonResult SubmitDoTask(User user, long taskId, long studentTaskId, string doWorkResults)
{
HttpContextHelper.RemoveCookie(cookieName => cookieName.IndexOf(string.Format(PrepDoTaskModel.CookieNameFormat, studentTaskId, string.Empty)) == 0);
//将doWorkResults转化为 DoWorkResult类型
var taskWorkResults = JsonConvert.DeserializeObject<IEnumerable<DoWorkResult>>(doWorkResults);
var task = this.guidedPlanTaskService.GuidedPlanTaskGet(taskId);
var myTask = this.studentTaskService.StudentTaskGet(studentTaskId);
var guidedPlan = this.guidedPlanService.GetGuidedPlanByID(task.GuidedPlanID);
........
return Json(new
{
isSuccess = true,
message = "操作成功。"
});
}