Asp.net MVC 使用json数据格式交互 示例
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Collections; namespace MvcApplicJson.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "欢迎使用 ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } public class Person { public string Name { set; get; } public string Sex { set; get; } } public JsonResult Child2() { Person perA = new Person() { Name = "李四",Sex="男" }; Person perB = new Person() { Name = "张三",Sex="女"}; List<Person> list = new List<Person>(); list.Add(perA); list.Add(perB); JsonResult jsonResult = Json(list, JsonRequestBehavior.AllowGet); return jsonResult; } } }
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 主页 </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2><%: ViewData["Message"] %></h2> <p> 若要了解有关 ASP.NET MVC 的更多信息,请访问 <a href="http://asp.net/mvc" title="ASP.NET MVC 网站">http://asp.net/mvc</a>。 </p> <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script type="text/javascript"> function test() { ///第一种方式 $.ajax({ url: "/Home/Child2", type: "get", dataType: "json", success: function (data) { for (var n = 0; n < data.length; n++) { alert("姓名:" + data[n].Name + "\n 年龄:" + data[n].Sex); } } }); ///第二种方式 $.getJSON("/Home/Child2", null, function (data) { for (var n = 0; n < data.length; n++) { alert("姓名:"+data[n].Name +"\n 年龄:"+data[n].Sex); } }) } </script> <input type="button" id="btns" value="JSON交互" onclick="test()"/> </asp:Content>