controller 中定義以下方法:
public JsonResult UpdateSingle(int id, string actionName, string actionValue) { var res = new JsonResult(); //var value = "actionValue"; //db.ContextOptions.ProxyCreationEnabled = false; var list = (from a in db.Articles select new { name = a.ArtTitle, yy = a.ArtPublishTime }).Take(5); //記得這裡要select new 否則會報錯:序列化類型 System.Data.Entity.DynamicProxies XXXXX 的對象時檢測到循環引用。 //不select new 也行的加上這句 //db.ContextOptions.ProxyCreationEnabled = false; res.Data = list;//返回列表 var name = "小華"; var age = "12"; var name1 = "小華"; var age1 = "12"; res.Data = new object[] { new { name, age }, new { name1, age1 } };//返回一個自定義的object數組 var person = new { Name = "小明", Age = 22, Sex = "男" }; res.Data = person;//返回單個對象; res.Data = "這是個字符串";//返回一個字符串,意義不大; res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允許使用GET方式獲取,否則用GET獲取是會報錯。 return res; }
頁面調用:
<a href="javascript:void(0);" onclick="javascript:upclick(this);">Click Me</a> <script type="text/javascript"> function upclick(o) { var obj = $(o); alert(obj); $.ajax({ url: "/Articles/UpdateSingle?ran=" + Math.random(), type: "GET", dataType: "json", data: { id: obj.attr("id"), actionName: obj.attr("actionName"), actionValue: obj.attr("actionValue") }, success: function (data) { // if (data.result == "True") { // alert("修改成功!"); // } // if (obj.attr("actionName") == "ArtVerify") { // } $(o).html(data[0].name); obj.attr("actionValue", data[0].result); } }) } </script>
以上是在mvc中使用,在webform中怎麼使用呢?
在webform中要引用Newtonsoft.Json.dll;
當然你也可以自己拼接字符串。
protected void Page_Load(object sender, EventArgs e) { var customer = new customer { name = "李華", sex = "男" }; var customer1 = new customer { name = "小芳", sex = "女" }; var li = new List<customer>(); li.Add(customer); li.Add(customer1); var list = Newtonsoft.Json.JavaScriptConvert.SerializeObject(li); var tt = "[{\"name\":\"李華\",\"sex\":\"男\"},{\"name\":\"小芳\",\"sex\":\"女\"}]"; //new Newtonsoft.Json.JsonSerializer()..(customer); Response.Write(tt); Response.End(); } public class customer { public string name { get; set; } public string sex { get; set; } }
頁面方法:
<p> <a href="javascript:void(0)" onclick="javascript:getJsonData();">GetJsonData</a> </p> <div id="dataDiv"> ggg </div> <script type="text/javascript"> function getJsonData() { var str = ""; $.getJSON("/Json.aspx", function (data) { var tt = ""; $.each(data, function (k, v) { $.each(v, function (kk, vv) { tt += kk + ":" + vv + "<br/>"; }); }); $("#dataDiv").html(tt); }); } </script>
顯示結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。