AJAX,JSON与MVC

有几个特殊之处

1. MVC框架中包含了一个特殊的JSONActionResult,可以直接返回JSON对象,注意它的格式与之前的asmx和页面静态方法都不一样,它直接就是一个JSON对象

2. 服务端和客户端编程都相对简单了。服务器端无须明确序列化,而客户端也无须解析JSON字符串了,因为返回的结果本来就是一个JSON对象

第一部分:Controller中的设计

  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Web; 
  5. using System.Web.Mvc; 
  6.  
  7. namespace MvcApplication1.Controllers 
  8.  
  9.     public class Employee 
  10.     { 
  11.         public int Id { getset; } 
  12.         public string Name { getset; } 
  13.     } 
  14.  
  15.     [HandleError] 
  16.     public class HomeController : Controller 
  17.     { 
  18.         public ActionResult Index() 
  19.         { 
  20.             ViewData["Message"] = "Welcome to ASP.NET MVC!"
  21.  
  22.             return View(); 
  23.         } 
  24.  
  25.         public ActionResult About() 
  26.         { 
  27.             return View(); 
  28.         } 
  29.  
  30.         public ActionResult Employee() { 
  31.             return View(); 
  32.         } 
  33.  
  34.  
  35.         [HttpPost] 
  36.         public ActionResult GetEmployee() { 
  37.             return Json(new Employee() 
  38.             { 
  39.                 Id = 1, 
  40.                 Name = "chenxizhang" 
  41.             }); 
  42.         } 
  43.  
  44.     } 

第二部分:View中的设计

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
  2.  
  3. <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"
  4.     GetEmployee 
  5. </asp:Content> 
  6. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"
  7.  
  8.     <script src="../../Scripts/jquery-1.3.2-vsdoc.js" type="text/javascript"></script> 
  9.  
  10.     <script type="text/javascript" language="javascript"
  11.         $(function() { 
  12.             $("#bt").click(function() { 
  13.                 $.ajax({ 
  14.                     type: "POST"
  15.                     contentType: "application/json"
  16.                     url: "http://localhost:44203/Home/GetEmployee"
  17.                     data: "{}"
  18.                     dataType: 'json'
  19.                     success: function(result) { 
  20.                         alert(result.Id); 
  21.                     } 
  22.  
  23.                 }); 
  24.             }); 
  25.         }); 
  26.      
  27.     </script> 
  28.  
  29.     <h2> 
  30.         GetEmployee</h2> 
  31.     <input type="button" value="Invoke" id="bt" /> 
  32.     <div id="info"
  33.     </div> 
  34. </asp:Content> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值