有幾個特殊之處
1. MVC架構中包含了一個特殊的JSONActionResult,可以直接返回JSON對象,注意它的格式與之前的asmx和頁面靜態方法都不一樣,它直接就是一個JSON對象
2. 服務端和用戶端編程都相對簡單了。伺服器端無須明確序列化,而用戶端也無須解析JSON字串了,因為返回的結果本來就是一個JSON對象
第一部分:Controller中的設計
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MvcApplication1.Controllers{ public class Employee { public int Id { get; set; } public string Name { get; set; } } [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } public ActionResult Employee() { return View(); } [HttpPost] public ActionResult GetEmployee() { return Json(new Employee() { Id = 1, Name = "chenxizhang" }); } }}
第二部分:View中的設計
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> GetEmployee</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <script src="../../Scripts/jquery-1.3.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> $(function() { $("#bt").click(function() { $.ajax({ type: "POST", contentType: "application/json", url: "http://localhost:44203/Home/GetEmployee", data: "{}", dataType: 'json', success: function(result) { alert(result.Id); } }); }); }); </script> <h2> GetEmployee</h2> <input type="button" value="Invoke" id="bt" /> <div id="info"> </div></asp:Content>