2010年11月29日 星期一

jQuery Ajax Mvc Part 4 - POST + Response List Json (傳回List方式的Json型態資料)

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過POST方式呼叫給Controller中的Action,透過Action處理後(查詢或存取後端資料庫處理元件),Return一個Json類型的資料及時回應給使用者所瀏覽的網頁上。


首先使用VS Web Developer 2010 Express建立一個ASP.NET MVC的專案。


首先得引用jQuery,這裡我們使用Google API的方式,當然也可以將jQuery的相關js檔案直接加入我們的專案檔中來使用。

   1:  <script type="text/javascript" src="https://ajax.googleapis.com
        /ajax/libs/jquery/1.4.3/jquery.min.js"></script>
   2:  <script type="text/javascript" src="https://ajax.googleapis.com
        /ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>

我們再/Models內建立一個Product類別,如下:


   1:  public class Product
   2:  {
   3:      public string Name { get; set; }
   4:      public int Price { get; set; }
   5:  }

接著,我們在HomeController中,加上兩個Action,可看到我們需標示這是一個JsonResult的Action與return出Json型態資料,如下:


   1:  public ActionResult jQueryDemo4()
   2:  {
   3:      return View();
   4:  }
   5:   
   6:  public JsonResult jQueryGetProductJson()
   7:  {
   8:      List<Product> list = new List<Product>();
   9:      list.Add(new Product { Name = "P001", Price = 1100 });
  10:      list.Add(new Product { Name = "P002", Price = 1300 });
  11:      list.Add(new Product { Name = "P003", Price = 2300 });
  12:      return Json(list);
  13:  }

並且建立一個jQueryDemo4.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.url:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryGetProductJson這個Action。
2.type:我們使用POST的方式。
3.async:true表示我們需要使用同步即時的方式取得Server回應。
4.data:{},這個範例並沒有傳給jQueryGetProductJson這個Action任何參數。
5.datatype:"json",表示我們回傳回來的是json型態資料。
6.success:在這裡我們以html格式顯示至id=Results的<div>區塊內。
7.each():Ajax讀取迴圈資料的語法,因目前回應的Jason資料型態中包含List資料,故我們使用.each()語法,並透過操作d這個物件,將Name與Price這些資料欄位的值一一讀出,當然也可使用for...next這類的讀取語法。


   1:  <h2>jQuery Ajax Mvc POST + Response JSON</h2>
   2:  <p>用POST方式,自Server取回JSON類型資料
   3:      (一個List->包含數個Product物件資料)</p>
   4:  <script type="text/javascript">
   5:      $(document).ready(function () {
   6:          $('#btnSubmit').click(function () {
   7:              $.ajax({
   8:                  url: "/Home/jQueryGetProductJson",
   9:                  type: "POST",
  10:                  async: true,
  11:                  data: {},
  12:                  dataType: "json",                    
  13:                  success: function (data) {
  14:                      var result = '';
  15:                      $.each(data, function (index, d) {
  16:                          if (d.Name != '') {
  17:                              result += "Product Name:" +
  18:                               d.Name + " | ";
  19:                              result += "Price:" +
  20:                               d.Price + "<br/>";
  21:                          }
  22:                      });
  23:                      $("#Results").html(result);
  24:                  }
  25:              })
  26:          }); 
  27:      });
  28:  </script>        
  29:  <input id="btnSubmit" type="submit"/>
  30:  <div id="Results"></div>

我們就可以執行這個MVC專案,我們點選Demo4這個頁籤,如下圖:


然後按下Submit按鈕後,就可呈現Ajax即時回應資料的網頁體驗,如下圖:

沒有留言:

張貼留言