2010年11月30日 星期二

jQuery Ajax Mvc Part 7 - jQuery UI Progress Bar

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過透過POST方式呼叫給Controller中的Action,經過Action處理後(可能是查詢或存取後端資料庫處理元件),透過jQuery UI progress bar的介面方式,回應目前系統處理狀態在使用者所瀏覽的網頁上。


首先使用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>

接著,我們在HomeController中,加上兩個Action,可看到我們為了拉長Action處理時間,特別加上sleep()方法以更明顯來觀察progress bar的變化,並且回應一個「處理完成」的字串訊息如下:


   1:  public ActionResult jQueryDemo7()
   2:  {
   3:      return View();
   4:  }
   5:   
   6:  public ActionResult jQueryProgressBar()
   7:  {
   8:      for (int i = 0; i < 10; i++)
   9:      {
  10:          Thread.Sleep(100);
  11:      }
  12:      Response.Write("處理完成");
  13:      return null;
  14:  }

並且建立一個jQueryDemo7.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.URL:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryProgressBar這個Action。
2.type:我們使用POST的方式。
3.async:true表示我們需要使用同步即時的方式取得Server回應。
4.data:{},就是我們要這個範例並沒有傳給jQueryProgressBar這個Action任何參數。
5.datatype:"text",表示我們回傳回來的是text型態資料。
6.success:若執行完畢,則讓progress bar顯示長度為100%,並以html格式顯示「處理完成」的字串訊息至id=Results的<div>區塊內。




   1:  <h2>jQuery Ajax Mvc - jQuery UI Progress Bar</h2>
   2:  <p>使用jQuery UI 的prpgress bar效果</p>
   3:  <script type="text/javascript" language="javascript">
   4:  $(document).ready(function () {
   5:      $("#progressbar").progressbar({ value: 0 });
   6:      $("#btnSubmit").click(function () {
   7:          var intervalID = setInterval(updateProgress, 100);
   8:          $.ajax({                   
   9:              url: "/Home/jQueryProgressBar",
  10:              type: "POST",
  11:              async: true,
  12:              data: {},
  13:              dataType: "text",              
  14:              success: function (data) {
  15:                  $("#progressbar").progressbar("value", 100);
  16:                  $("#Results").html(data);
  17:                  clearInterval(intervalID);
  18:              }                  
  19:          });
  20:          return false;
  21:      });
  22:  });
  23:   
  24:  function updateProgress() {
  25:      var value = $("#progressbar").progressbar("option", "value");
  26:      if (value < 100) {
  27:          $("#progressbar").progressbar("value", value + 1);
  28:      }
  29:  }                
  30:  </script>
  31:   
  32:  <div id="progressbar"></div>
  33:  <div id="Results"></div><br />                             
  34:  <input type="button" id="btnSubmit" value="Submit" />   

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


然後按下Submit按鈕後,就看到隨著處理時間經過而顯示灰色bar由短變長的jQuery UI progress bar效果,如下圖:


系統處理完成後,我們收到Action傳來的「處理完成」的字串訊息,如下圖:

jQuery Ajax Mvc Part 6 - Response Json use .getJSON() + Display with ListItem(將資料傳回後放入ListItem中)

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


首先使用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>


接著,我們在HomeController中,加上兩個Action,可看到我們需標示這是一個JsonResult的Action與return出Json型態資料;因為我們MVC這邊預設不用get方式,所以當我們使用到jQuery的.getJSON()時,須特別加上JsonRequestBehavior.AllowGet這個准許使用get的設定,如下:


   1:  public ActionResult jQueryDemo6()
   2:  {
   3:      return View();
   4:  }
   5:   
   6:  public JsonResult jQueryGetListItem()
   7:  {
   8:      List<ListItem> list = new List<ListItem>() {
   9:          new ListItem() { Text = "2001太空漫遊 /
                                2001: A Space Odyssey" },
  10:          new ListItem() { Text = "銀翼殺手 / Blade Runner" },
  11:          new ListItem() { Text = "ET /
                                E.T. the Extra-Terrestrial" },
  12:          new ListItem() { Text = "消失的1943 / 
                                The Philadelphia Experiment" },
  13:          new ListItem() { Text = "魔鬼終結者 / The Terminator" },
  14:          new ListItem() { Text = "異形 / Aliens" },
  15:          new ListItem() { Text = "星際爭霸戰 / Star Trek XI" }
  16:      };
  17:      return this.Json(list, JsonRequestBehavior.AllowGet);
  18:  }

並且建立一個jQueryDemo6.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.each():Ajax讀取迴圈資料的語法,因目前回應的Jason資料型態中包含List資料,故我們使用.each()語法,將Action的itemData資料欄位值一一讀出,然後加到list這個變數中。
2.getJSON():我們使用Get的方式取得Json型態的回應資料(可参考jQuery文件),有3個参數需留意:


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


被執行的URL就是上面程式碼中的HomeController中的jQueryGetListItem這個Action,然後把執行後回應的結果資料填入itemList的Html標籤中。



   1:  <script type="text/javascript">
   2:  $('#itemsList').disableSelection();
   3:  $.fn.addItems = function (data) {
   4:      return this.each(function () {
   5:          var list = this;
   6:          $.each(data, function (index, itemData) {
   7:              var option = new Option(itemData.Text);
   8:              list.add(option);
   9:          });
  10:      });
  11:  };
  12:   
  13:  $(function () {
  14:      $('#itemsList').show();
  15:      $('#btnSubmit').click(function () {
  16:          $.getJSON("/Home/jQueryGetListItem",
  17:             null, function (data) {
  18:              $("#itemsList").addItems(data);
  19:          });
  20:      });
  21:  });
  22:  </script>
  23:  <button id="btnSubmit" name="btnClick">
  24:      科幻電影Science Fiction Films</button>
  25:  <br />
  26:  <select id="itemsList" name="itemsList">
  27:  </select>

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


然後按下「科幻電影Science Fiction Films」按鈕(Submit)後,就可呈現Ajax即時回應資料的網頁體驗,且這裡是以ListItem的下拉清單方式呈現科幻電影的名稱如下圖:

2010年11月29日 星期一

文章分類: jQuery



2010-12-8 星期三

jQuery Ajax Mvc Part 8 - jQuery UI Progress Bar + Json

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過透過POST方式呼叫給Controller中的Action,經過Action處理後(可能是查詢或存取後端資料庫處理元件),透過jQuery UI progress bar的介面方式,回應目前系統處理狀態在使用者所瀏覽的網頁上,最後顯示Action處理後的Json型態資料。
....MORE




2010-11-30 星期二

jQuery Ajax Mvc Part 7 - jQuery UI Progress Bar

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過透過POST方式呼叫給Controller中的Action,經過Action處理後(可能是查詢或存取後端資料庫處理元件),透過jQuery UI progress bar的介面方式,回應目前系統處理狀態在使用者所瀏覽的網頁上。
....MORE




2010-11-30 星期二

jQuery Ajax Mvc Part 6 - Response Json use .getJSON() + Display with ListItem(將資料傳回後放入ListItem中)

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



2010-11-29 星期一

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

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




2010-11-29 星期一

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

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




2010-11-29 星期一

jQuery Ajax Mvc Part 3 - POST Parm + Response Data(傳遞參數與回應Html型態字串資料)

在這個例子MVC的架構中,希望能夠套用jQuery .Ajax()的方式,透過POST方式,將網頁上輸入兩個参數給Controller中的Action,將過Actiont處理後(查詢或存取後端資料庫處理元件),及時回應一群資料給使用者所瀏覽的網頁上。....MORE




2010-11-29 星期一

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

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




2010-10-3 星期三

jQuery Ajax Mvc Part 1 - POST + Get Message(POST參數並同步接收Server回應的文字訊息)

我們在MVC的架構中,希望能夠套用jQuery .Ajax()的方式,將參數POST到Server某一個Action中,然後在原來的View中接收這個Server中Action的回應資料。就好像一般MVC架構中,最典型的流程,即是POST一個Form或者是一些參數值到一個Controller的Action中,然後這個Action再將回應資料,回應給某一個View。
這裡也主要也是這樣的流程,不過我們希望透過使用jQuery的Ajax方是,可以同步取得Action中的回應,然後及時回應給使用者的網頁上,當然,因為我們使用Ajax,所以使用者不會有redirect到另外一頁的感覺。....MORE


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即時回應資料的網頁體驗,如下圖:

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即時回應資料的網頁體驗,如下圖:

jQuery Ajax Mvc Part 3 - POST Parm + Response Data(傳遞參數與回應Html型態字串資料)

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


首先使用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,我們將資料簡化存在List型態變數中,然後用StringBuilding將傳入参數與資料包成Html碼輸出到前端網頁顯示出來,如下:


   1:  public ActionResult jQueryDemo3()
   2:  {
   3:      return View();
   4:  }
   5:   
   6:  public ActionResult jQueryGetProductData(string uName, string uCity)
   7:  {
   8:      List<Product> list = new List<Product>();
   9:      list.Add(new Product { Name = "B001", Price = 1320 });
  10:      list.Add(new Product { Name = "B002", Price = 3301 });
  11:      list.Add(new Product { Name = "B003", Price = 2623 });
  12:      list.Add(new Product { Name = "B004", Price = 1320 });
  13:      list.Add(new Product { Name = "B005", Price = 3301 });
  14:      list.Add(new Product { Name = "B006", Price = 2623 });
  15:      StringBuilder sb = new StringBuilder();
  16:      sb.Append("Customer ID:" + uName +
  17:          "<br/>City:" + uCity + "<br/>");
  18:      foreach (Product p in list)
  19:      {
  20:          sb.Append("Product Name:" + p.Name +
  21:              "  |  Price:" + p.Price  + "<br/>");
  22:      }
  23:      Response.Write(sb.ToString());
  24:      return null;
  25:  }

並且建立一個jQueryDemo3.aspx的View,然後加上jQuery的.ajax()語法,說明如下:
1.url:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryGetProductData這個Action。
2.type:我們使用POST的方式。
3.async:true表示我們需要使用同步即時的方式取得Server回應。
4.data:我們取得網頁上輸入的客戶的Name與City兩個TextBox的值,對應並傳遞給jQueryGetProductData這個Action兩個参數,uName與uCity。
5.datatype:"text",表示我們回傳回來的是text型態資料。
6.success:在這裡我們以html格式顯示至id=Results的<div>區塊內。


   1:  <h2>jQuery Ajax Mvc POST Parm + Get Data</h2>
   2:  <p>用POST方式,自Server取回Html類型資料(一個List->包含數個Product物件資料)</p>
   3:  <script type="text/javascript">
   4:      $(document).ready(function () {
   5:          $('#btnSubmit').click(function () {
   6:              $.ajax({
   7:                  url: "/Home/jQueryGetProductData",
   8:                  type: "POST",
   9:                  async: true,
  10:                  data: "uName=" + $("#Name").val() + "&uCity=" + $("#City").val(),
  11:                  datatype: "text",
  12:                  success: function (data) {
  13:                      $("#Results").html(data);
  14:                  }
  15:              });
  16:          });
  17:      });    
  18:  </script>
  19:  Customer's Name:<input id="Name" type="text" /><br />
  20:  Customer's City:<input id="City" type="text" /><br />
  21:  <input id="btnSubmit" type="submit" value="Submit"/>
  22:  <div id="Results"></div>

我們就可以執行這個MVC專案,我們點選Demo3這個頁籤,並輸入客戶的Name與City如下圖:


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

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即時回應資料的網頁體驗,如下圖:

2010年11月3日 星期三

jQuery Ajax Mvc Part 1 - POST + Get Message(POST參數並同步接收Server回應的文字訊息)

我們在MVC的架構中,希望能夠套用jQuery .Ajax()的方式,將參數POST到Server某一個Action中,然後在原來的View中接收這個Server中Action的回應資料。就好像一般MVC架構中,最典型的流程,即是POST一個Form或者是一些參數值到一個Controller的Action中,然後這個Action再將回應資料,回應給某一個View。

這裡也主要也是這樣的流程,不過我們希望透過使用jQuery的Ajax方是,可以同步取得Action中的回應,然後及時回應給使用者的網頁上,當然,因為我們使用Ajax,所以使用者不會有redirect到另外一頁的感覺。


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


要使用jQuery,得先引用jQuery的library,這裡我們使用Google API的方式,當然也可以將jQuery的相關js檔案直接引用到我們的專案檔的主頁/View/Shared/Site.Master來使用。


   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>

接著,我們在HomeController中,加上兩個Action,如下:


   1:  public ActionResult jQueryDemo1()
   2:  {
   3:      return View();
   4:  }
   5:   
   6:  public ActionResult jQueryGetWelcomeMsg(string id)
   7:  {
   8:      string msg = "<p>Hello! " + id + "!<br/>" + 
   9:          "<img src='/Content/world.png' alt='earth'/></p>";
  10:      Response.Write(msg);
  11:      return null;
  12:  }

並且建立一個jQueryDemo1.aspx的View,然後加上下列jQuery的.ajax()語法,說明如下:
1.url:這裡就是我們MVC架構中,我們要POST的/{Controller}/{Action},就是上面程式碼中的HomeController中的jQueryGetWelcomeMsg這個Action。
2.type:"POST":我們使用POST的方式。
3.async:true表示我們需要使用同步即時的方式取得Server回應。
4.data:"id=HoraceLin",就是我們要傳給jQueryGetWelcomeMsg這個Action一個參數,這個參數名稱為id,其帶入的值為HoraceLin。
5.datatype:"text",表示我們回傳回來的是文字型態資料,並顯示在id=Results的<div>中。


   1:      <h3>jQuery Ajax - POST & Get Message</h3>
   2:      <p>POST 參數給Server,並接收文字資料</p>
   3:      <script type="text/javascript">
   4:          $(function () {
   5:              $('#btnSubmit').click(function () {
   6:                  $.ajax({
   7:                      url: "/Home/jQueryGetWelcomeMsg",
   8:                      type:"POST",
   9:                      cache: false,
  10:                      async: true,
  11:                      data: "id=HoraceLin",
  12:                      datatype: "text",
  13:                      success: function (data) {
  14:                          $("#Results").html(data);
  15:                      }
  16:                  });
  17:              });
  18:          });  
  19:      </script>
  20:      <input id="btnSubmit" type="submit" value="Submit" />
  21:      <div id="Results">
  22:      </div>

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



然後按下Submit按鈕後,就從Server端HomeController的Action中,回應text型態的一些Html碼,這裡就可呈現Ajax即時回應資料的網頁體驗,如下圖:



未來的一些文章中,將陸續示範jQuery Ajax運用在MVC的範例。