日期:2014-05-18 浏览次数:20531 次
using System; using System.Collections; using System.Web; using System.Web.Script.Serialization; namespace Lab.Web { public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { var data = new Hashtable(); data["success"] = true; data["now"] = DateTime.Now; data["message"] = "En Taro Adun!"; var jss = new JavaScriptSerializer(); var json = jss.Serialize(data); context.Response.ContentType = "text/javascript"; context.Response.Write(json); } public bool IsReusable { get { return false; } } } }
------解决方案--------------------
//返回集合跟返回对象是一样的处理模式
前端交互
$.ajax({
type: "get",
url: "@Url.Action("ShowDetail","UserInfo")",
data: "ID="+id,
dataType:"json",
success: function (msg) { //msg是一个对象 如果是集合的话就要msg[i].UserName 来获取UserName这个属性的值
$("#DUserName").val(msg.UserName);
$("#Dpwd").val(msg.pwd);
$("#Daddress").val(msg.address);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
//后台处理
public JsonResult ShowDetail() {
var id = Convert.ToInt32(Request["id"].ToString());
UserInfo u = db.UserInfo.Single(ui=>ui.id== id); //根据id查询单个对象
U里面有UserName pwd address 等属性
return Json(u,JsonRequestBehavior.AllowGet);
//这里是返回单个对象 返回list也类似
}