標籤:返回 技術分享 test tar lin table 設計 javascrip 前台
之前寫過ajax和一般處理常式的結合實現前背景資料交換的部落格,如今做系統用到了MVC,同一時候也用到了非同步擷取資料。
ajax+一般處理常式與MVC+ajax原理是一樣的在"URL"中前者寫的一般處理常式的名字。而後者寫到Controller中須要調用的方法。
Controller中的設計
using System.Collections.Generic;using System.Web.Mvc;namespace mvcAjaxByAjax.Controllers{ //考試試題 public class ExamEntity { public int Id { get; set; } public string ExamName { get; set; } } public class mvcAjaxByAjaxController : Controller { [HandleError] public ActionResult Index() { return View(); } /// <summary> /// 擷取考試資料 /// </summary> /// <returns></returns> [HttpPost] public ActionResult GetExam() { //加入employee資料 List<ExamEntity> examList = new List<ExamEntity>() { new ExamEntity {Id = 1, ExamName = "語文考試"}, new ExamEntity {Id = 2, ExamName = "數學考試"} }; //直接返回此類型JSON類型 return Json(examList); } }}
View中的設計
@{ ViewBag.Title = "Index";}<script src="~/Scripts/jquery-2.1.3.min.js"></script><h2>ajax擷取資料</h2><script type="text/javascript" language="javascript"> $(function () { //注冊單擊事件 $("#btTest").click(function() { $.ajax({ type: "POST", contentType: "application/json", url: "GetExam", data: "{}", dataType: 'json', success: function (result) { //將返回資料加入到頁面表格中 $("#tdId1").html(result[0].Id); $("#tdName1").html(result[0].ExamName); $("#tdId2").html(result[1].Id); $("#tdName2").html(result[1].ExamName); } }); }); }); </script><table> <tr> <th>考試ID</th> <th>考試名稱</th> </tr> <tr> <td id="tdId1"></td> <td id="tdId2"></td> </tr> <tr> <td id="tdName1"></td> <td id="tdName2"></td> </tr> <tr> <td><input type="button" value="查詢" id="btTest" /></td> </tr></table>
通過firebug 查看返回的資料
頁面顯示效果
總結
利用mvc+ajax簡單的實現非同步資料的查詢,直接調用背景Controllers方法。後台方法直接返回資料給前台控制項。
MVC—實現ajax+mvc非同步擷取資料