ASP.NET MVC + jQuery + Newtonsoft.Json 快乐的AJAX


这是目前我的方案,个人觉得还蛮轻巧自在的。 Controller负责把要输出的资料序列成json。

  Html.ActionUrl 这只method原来的MVC Toolkit没有,我随手加的。

  我 是用Newtonsoft.Json作物件序列成JSON,那为什麽不用MS Ajax内建的 System.Web.Script.Serialization.JavaScriptSerializer 来做,是因为他将DateTime序列成字串格式,Client 端无法直接取用。Newtonsoft.Json的部份我也是小改一点,让他可以做Value Type 的序列化,可参考。

  附带一提,我是架在iis 5.1上测试,本来看到 IIS 6.0 和 ASP.NET 3.5 / VS 2008 的相容性测试,己为会很困难的,大概是测MVC Web Project比较单纯吧,装完 .NET Framework 3.5 再装 ASP.NET 3.5 Extensions Preview (是的,目前只是preview版),直接就ok了。

  底 下的流程 Controller(AjaxTest) -> View(AjaxPage) -> Controller(Ajax, id=1) -> View(AjaxPage) 取得json ->Controller(Ajax, id=2) -> View(AjaxPage) 取得json -> end ,大概是这样。(如果画成图会比较漂亮吧)

ControllerBase.cs
  public class ControllerBase : Controller {
    public void RenderJSON(object obj) {
      string jsonString = Newtonsoft.Json.JavaScriptConvert.SerializeObject(obj);
      Response.Clear();
      Response.ContentEncoding = Encoding.UTF8;
      Response.ContentType = "application/json";
      Response.Write(jsonString);
      Response.Flush();
      Response.End();
    }
  }
HomeController.cs
  public class HomeController : ControllerBase {
    [ControllerAction]
    public void AjaxTest() {
      RenderView("AjaxPage");
    }
    [ControllerAction]
    public void Ajax(int id) {
      switch (id) {
        case 1:       
          RenderJSON(DateTime.Now.ToString());          
          break;
        case 2:
          Order[] orders = new Order[] {
            new Order() {PK=1, Title="B001", OrderDate = DateTime.Now},
            new Order() {PK=2, Title="A003", OrderDate = DateTime.Now}
          };
          RenderJSON(orders);
          break;
        case 3:          
          int n1,n2;
          int.TryParse(Request["n1"],out n1);
          int.TryParse(Request["n2"],out n2);            
          RenderJSON(n1 + n2);
          break;
      }
    }
  }
}
AjaxPage.aspx
 <script language="javascript" type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.1.min.js"></script>
 <script language="javascript" type="text/javascript">
  $(document).ready(function() {
    var actionUrl1 = '<%=Html.ActionUrl("ajax", "/1") %>';
    var actionUrl2 = '<%=Html.ActionUrl("ajax", "/2") %>';
    var actionUrl3 = '<%=Html.ActionUrl("ajax", "/3") %>';
    $("#link1").click(function() {
      $.getJSON(actionUrl1, { }, function(json){
       alert("Server Time: " + json);
      });
    });
    $("#link2").click(function() {
      $.getJSON(actionUrl2, { }, function(json){
       alert("total " + json.length.toString() + " records");
       for(var i=0;i<json.length;i++) {
        alert(json[i].PK + ", " + json[i].Title + ", " + json[i].OrderDate);
       }       
      });
    });
    $("#t1,#t2").change(function() {
      $.getJSON(actionUrl3, { "n1": $("#t1").val(),"n2": $("#t2").val() }, function(json){
       $("#t3").val(json.toString());
      });
    });    
  });
 </script>
 <h3>
  Ajax Page</h3>
 <ol>
  <li><a id="link1" href="#">Get Server Time</a></li>
  <li><a id="link2" href="#">Return Object</a></li>
  <li>
   <input type="text" name="t1" id="t1" maxlength="4" style="width: 40px" />
   +
   <input type="text" name="t2" id="t2" maxlength="4" style="width: 40px" />
   =
   <input type="text" name="t3" id="t3" maxlength="4" readonly="readonly" style="width: 40px" />
  </li>  
 </ol>

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3