MVC中处理Json和JS中处理Json对象
ASP.NET MVC 很好的封装了Json,本文介绍MVC中处理Json和JS中处理Json对象,并提供详细的示例代码供参考。
MVC中已经很好的封装了Json,让我们很方便的进行操作,而不像JS中那么复杂了。
JsonResult 传值
MVC中:
public JsonResult Test() { JsonResult json = new JsonResult{ Data = new{ Name = "zzl", Sex = "male",} }; // Name、Sex为可自定义的属性名 return Json(json); }
public JsonResult TestList() { List<User> userList = new List<User> { new User{Name="zzl",Email="bfyxzls@sina.com"}, new User{Name="zhz",Email="zhanghangzheng@sina.com"}, }; JsonResult json = new JsonResult{ Data = userList }; return Json(json); }
前台调用:
<script> $.ajax({ url: "/Home/Test", dataType: "json", cache: false, data: null, type: "POST", success: function (data) { alert(data.Data.Name); } }); $.ajax({ url: "/Home/TestList", dataType: "json", cache: false, data: null, type: "POST", success: function (data) { var msg = ""; for (var i = 0, length = data.Data.length; i < length; i++) { msg += "<DiV>Name:" + data.Data[i].Name + ",Email:" + data.Data[i].Email + "</div>"; } $("#msg2").html(msg); } }); </script>
直接传值
public JsonResult Test()
{
var json = new{ Name = "zzl", Sex = "male",} };
return Json(json);
}
public JsonResult TestList() { List<User> userList = new List<User> { new User{Name="zzl",Email="bfyxzls@sina.com"}, new User{Name="zhz",Email="zhanghangzheng@sina.com"}, }; return Json(userList); }
jq
$.ajax({ url: "/Home/TestList", dataType: "json", cache: false, data: null, type: "POST", success: function (data) { var msg = "<table border=1><thead><tr><td>Name</td><td>Email</td></tr></thead><tbody>"; for (var i = 0, length = data.length; i < length; i++) { msg += "<tr><td>" + data[i].Name + "</td><td>" + data[i].Email + "</td></tr>"; } msg += "</body></table>"; $("#msg2").html(msg); } });
纯JS进行操作:
var arr = [{ "name": "zzl", "sex": "男" }, { "name": "lr", "sex": "女"}]; for (var i = 0; i < arr.length;i++ ) { document.write(arr[i].name); }
推荐文章:
mvc的Controller返回值类型ActionResult详解
原文:http://www.cnblogs.com/lori/archive/2011/08/25/2153479.html