mvc4 如何返回Json数据并且 前台中怎么取它后台返回的数据
1个回答
展开全部
前台ajax请求
function loadDoctorInfo(departmentID){
$.ajax({
url:"@Url.Content("~/Doctor/GetInfo")",
data:{departmentID:departmentID},
async:true,
success:function(result){
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(result);
$("#myContainer").html(html);
},
error:function(result,errorInfo){
alert("加载医生信息失败");
}
});
}
后台返回json数据
public JsonResult GetInfo(int departmentID=0)
{
if(departmentID<=0)
{
return Json(new { state = false, msg = "科室信息有误" }, JsonRequestBehavior.AllowGet);
}
var doctors = dbContext.Doctors.Where(p=>p.DepartmentID==departmentID);
if(doctors==null||doctors.Count()<=0)
{
return Json(new { state = false, msg = "该科室暂无医生信息" }, JsonRequestBehavior.AllowGet);
}
var result = doctors.Select(p => new {
ID=p.ID,
Name=p.Name,
Abstract=p.Abstract,
LevelTitle=p.LevelTitle,
Expertise=p.Expertise
});
return Json(new { state = true, msg = "加载成功" ,data=result}, JsonRequestBehavior.AllowGet);
}
function loadDoctorInfo(departmentID){
$.ajax({
url:"@Url.Content("~/Doctor/GetInfo")",
data:{departmentID:departmentID},
async:true,
success:function(result){
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var html = template(result);
$("#myContainer").html(html);
},
error:function(result,errorInfo){
alert("加载医生信息失败");
}
});
}
后台返回json数据
public JsonResult GetInfo(int departmentID=0)
{
if(departmentID<=0)
{
return Json(new { state = false, msg = "科室信息有误" }, JsonRequestBehavior.AllowGet);
}
var doctors = dbContext.Doctors.Where(p=>p.DepartmentID==departmentID);
if(doctors==null||doctors.Count()<=0)
{
return Json(new { state = false, msg = "该科室暂无医生信息" }, JsonRequestBehavior.AllowGet);
}
var result = doctors.Select(p => new {
ID=p.ID,
Name=p.Name,
Abstract=p.Abstract,
LevelTitle=p.LevelTitle,
Expertise=p.Expertise
});
return Json(new { state = true, msg = "加载成功" ,data=result}, JsonRequestBehavior.AllowGet);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询