2010年11月29日 星期一

jQuery Ajax Mvc Part 2 - POST + Response Json(回應一個Json資料型態)

我們在MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過POST方式,自一個Controller的Action中,取回一個物件類型的資料,這個時候,我們可以使用上Return一個Json類型的資料及時回應給使用者所瀏覽的網頁上,當然因為我們使用Ajax,所以使用者感受到的是在同一網頁中即時就取得資料的感覺。


首先使用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 jQueryDemo2()
   2:  {
   3:     return View();
   4:  }
   5:   
   6:  public JsonResult jQueryGetSimpleJSON()
   7:  {
   8:      Product prd = new Product {
   9:          Name = "B002",
  10:          Price = 3301
  11:      };
  12:      return Json(prd);
  13:  }


並且建立一個jQueryDemo2.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.url:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryGetSimpleJSON這個Action。
2.type:我們使用POST的方式。
3.async:true表示我們需要使用同步即時的方式取得Server回應。
4.data:{},就是我們要這個範例並沒有傳給jQueryGetSimpleJSON這個Action任何參數。
5.datatype:"json",表示我們回傳回來的是Json型態資料。
6.success:在這裡我們可使用data.xxxx的方式將產品"B002"的名稱與價格資料讀出,並以html格式顯示至id=Results的<div>區塊內。



   1:  <h2>jQuery Ajax - POST & Response Json</h2>
   2:  <p>用POST方式,自Server取回JSON類型資料(一個Product物件資料)</p>
   3:  <script type="text/javascript">
   4:      $(document).ready(function () {
   5:          $('#btnSubmit').click(function () {
   6:              $.ajax({
   7:                  url: "/Home/jQueryGetSimpleJSON",
   8:                  type: "POST",
   9:                  async: true,
  10:                  data: {},
  11:                  dataType: "json",
  12:                  success: function (data) {
  13:                      $("#Results").html("<b>Product Name:</b>"
  14:                       + data.Name
  15:                       + "<br/><b>Price:</b>" + data.Price);
  16:                  }
  17:              })
  18:          });
  19:      });
  20:  </script>
  21:  <div>
  22:      <input type="button" id="btnSubmit" value="Submit"/>
  23:      <br />
  24:      <br />
  25:      <div id="Results">
  26:      </div>
  27:  </div>

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


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

沒有留言:

張貼留言