2010年11月29日 星期一

jQuery Ajax Mvc Part 5 - Get + Response Json use .getJSON() (使用.getJSON()方法取得資料)

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過.getJSON()的方式呼叫給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,透過傳入的参數Category來選擇輸出資料,可看到我們需標示這是一個JsonResult的Action與return出Json型態資料;因為我們MVC這邊預設不用get方式,所以當我們使用到jQuery的.getJSON()時,須特別加上JsonRequestBehavior.AllowGet這個准許使用get的設定,如下:


   1:  public ActionResult jQueryDemo5()
   2:  {
   3:      return View();
   4:  }
   5:  public JsonResult jQueryGetJsonByParm(string Category)
   6:  {
   7:      List<Product> list = new List<Product>();
   8:      if (Category == "A")
   9:      {
  10:         list.Add(new Product { Name = "A01", Price = 11 });
  11:         list.Add(new Product { Name = "A02", Price = 13 });
  12:         list.Add(new Product { Name = "A03", Price = 23 });
  13:      }
  14:      else
  15:      {
  16:         
  17:         list.Add(new Product { Name = "B01", Price = 13 });
  18:         list.Add(new Product { Name = "B02", Price = 33 });
  19:         list.Add(new Product { Name = "B03", Price = 26 });
  20:         list.Add(new Product { Name = "B04", Price = 13 });
  21:         list.Add(new Product { Name = "B05", Price = 33 });
  22:         list.Add(new Product { Name = "B06", Price = 26 });
  23:      }
  24:      return Json(list, JsonRequestBehavior.AllowGet);
  25:  }

並且建立一個jQueryDemo5.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.URL:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryGetJsonByParm這個Action。
2.getJSON():我們使用Get的方式取得Json型態的回應資料(可参考jQuery文件),
有3個参數需留意:


.getJSON()(被執行的URL,get的輸入参數,執行後回應的結果)


3.each():Ajax讀取迴圈資料的語法,因目前回應的Jason資料型態中包含List資料,故我們使用.each()語法,並透過操作 d 這個物件,將Name與Price這些資料欄位的值一一讀出,當然也可使用for...next這類的讀取語法。


   1:  <h2>jQuery Ajax Mvc - Get + Response Json use .getJSON()</h2>
   2:  <p>用.getJSON()方式,Send給Server一個(或數個)參數,
   3:  並自Server取回JSON類型資料(一個List->包含數個Product物件資料)</p>
   4:  <script type="text/javascript">
   5:      $(document).ready(function () {
   6:          $('#btnSubmit').click(function () {
   7:              var URL = "/Home/jQueryGetJsonByParm";
   8:              $.getJSON(URL, { Category: $("#Category").val() },
   9:                 function (data) {
  10:                  var resultA = '';
  11:                  $.each(data, function (index, d) {
  12:                      if (d.Name != '') {
  13:                          resultA += "Product Name:" 
  14:                              + d.Name + " | ";
  15:                          resultA += "Price:" 
  16:                             + d.Price + "<br/>";
  17:                      }
  18:                  });
  19:                  $("#Results").html(resultA);
  20:              });
  21:          });
  22:      });
  23:  </script>
  24:  Input A or B Category:<input id="Category" type="text" />
  25:  <input id="btnSubmit" type="submit" value="Submit"/>
  26:  <div id="Results">
  27:  </div>


我們就可以執行這個MVC專案,我們點選Demo5這個頁籤,並輸入A或B任一種類別,當然可自行加上一些驗證與檢核功能,如下圖:


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

沒有留言:

張貼留言