@H_403_0@Controller中的设计 @H_403_0@
@H_403_0@
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); } } }
@H_403_0@View中的设计 @H_403_0@
@H_403_0@
@{ 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>@H_403_0@
通过firebug 查看返回的数据 @H_403_0@
@H_403_0@
@H_403_0@页面显示效果 @H_403_0@
@H_403_0@
@H_403_0@总结 @H_403_0@ 利用mvc+ajax简单的实现异步数据的查询,直接调用后台的Controllers方法,后台方法直接返回数据给前台控件。