GET:
JS代码
$.ajax({ type: "GET", url: "/Category/Questions/1", dataType: "json", success: function (data) { if (!data.Error) { var result = $("#result3").html(); $(data).each(function (index, item) { result += ("Id: " + item.Id + ", Name: " + item.Name + "'/>") + "<br>"; }) $("#result3").html(result) } else { $("#result3").html("Error!<br>Error code: " + data.Code + "<br>Error messages: " + data.Messages) } } });
后台代码
public JsonResult Questions(int Id) { try { return Json(this._categoryQuestionService.GetQustionByCategoryId(Id), JsonRequestBehavior.AllowGet); } catch (Exception ex) { var error = new ErrorModel() { Code = 1, Error = true, Messages = ex.Message }; return Json(error, JsonRequestBehavior.AllowGet); } }
POST
JS代码
var answers = {
MemberId: 1,
Questions: [
{Id: 1,Name:'test1'},
{Id: 2,Name:'test2'},
{Id: 3,Name:'test3'}
]
};
$.ajax({ type: "POST", url: "/Category/Questions", dataType: "json", data: JSON.stringify(result), contentType: 'application/json; charset=utf-8', success: function (data) { if (!data.Error) { $("#result4").html("Sucess"); } else { $("#result4").html("Error!<br>Error code: " + data.Code + "<br>Error messages: " + data.Messages) } } });
.cs代码
[HttpPost] public JsonResult Questions(MemberAnswers memberAnswers) { try { foreach (PostAnswer item in memberAnswers.Questions) { //To do
} return Json(""); } catch (Exception ex) { var error = new ErrorModel() { Code = 1, Error = true, Messages = ex.Message }; return Json(error); } }
public class MemberAnswers { public string MemberId { get; set; } public List<PostAnswer> Questions { get; set; } } public class PostAnswer { public string Id { get; set; } public string Answer { get; set; } }