1.新建一个Project,Basic类型.
2.Models目录下创建一个Student.cs类文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcJSonTest.Models
{
public class Student
{
public string Name { set; get; }
public int Age { set; get; }
public bool Sex { set; get; }
}
}
2.HomeController.cs文件如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcJSonTest.Models;
namespace MvcJSonTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Second()
{
return View();
}
public JsonResult GetJson1()
{
var json = new {Name="张三",Age=18,Sex=true};
return Json(json,JsonRequestBehavior.AllowGet);
// return Json(new { Name = "张三", Age = 18, Sex = true }, JsonRequestBehavior.AllowGet);
}
public JsonResult GetJson2()
{
var json = new { Name = "李四", Age = 28, Sex = false };
var res = new JsonResult();
res.Data = json;
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return res;
}
public JsonResult GetJson3()
{
Student st = new Student();
st.Name = "王麻子";
st.Age = 88;
st.Sex = true;
return Json(st, JsonRequestBehavior.AllowGet);
// var res = new JsonResult();
// res.Data = st;
// res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
// return res;
}
}
}
3.Home/Index.cshtml文件如下:
@{
ViewBag.Title = "Index";
}
<h2>
PostShow</h2>
<div id="PostShow">
</div>
<hr />
<h2>
GetShow</h2>
<div id="GetShow">
</div>
<br />
@Html.ActionLink("Second", "Second")
@section scripts
{
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")">
</script>
@if (false)
{
<script src="/Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>
}
<script type="text/javascript" >
var sAge
$(function () {
$.ajax({
url: "/Home/GetJson1",
type: "POST",
dataType: "json",
data: {},
success: function (data) {
$("#PostShow").html(data.Name);
}
});
$.getJSON("/Home/GetJson2", function (data) {
$("#GetShow").html(data.Name+","+data.Age+","+data.Sex);
});
})
</script>
}
3.Second.cshtml代码如下:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Second</title>
</head>
<body>
<div id="test"></div>
<hr />
<div id="test2"></div>
<button id="btn1" >getJSON测试</button>
</body>
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(function () {
$("#btn1").click(function () {
$.getJSON("/Home/GetJson3", function (result) {
alert(result);
$("#test").append(result.Name);
$.each(result, function (i, data) {
$("#test2").append(i + ":" + data + "<hr/>");
});
});
});
});
</script>
</html>