MVC&JQuery如何根据List动态生成表格

背景:在编码中,常会遇到根据Ajax的结果动态生成Table的情况,本篇进行简要的说明。这已经是我第4、5篇和Ajax有关的随笔了,互相之间有很多交叠的地方,可自行参考。

后台代码如下:

 1         public ActionResult Index()
 2         {
 3             
 4             return View();
 5         }
 6 
 7 
 8         public ActionResult GetStus()
 9         {
10             List<Stu> ListStu = new List<Stu>(){
11                 new Stu{Age=18,City="北京",Name="SharpL"},
12                 new Stu{Age=18,City="北京",Name="Lily"},
13                 new Stu{Age=18,City="南京",Name="Lucy"}
14             };
15             return Json(ListStu);
16         }
View Code

以上的代码中,应用到Stu类,请自行构建。

HTML代码如下:

 1     <div>
 2         <button id="btnGenerate">生成学生表格</button>
 3         <table id="destTable"></table>
 4     </div>
 5     <table id="moban" style="display:none">
 6         <tr>
 7             <td>{Name}</td>
 8             <td>{Age}</td>
 9             <td>{City}</td>
10         </tr>
11     </table>

注意第二张表格是不显示的,只是作为JQuery中用来生成表格的模板使用,“destTable”是用来显示在页面上的。

JQuery代码如下:

 1     $(function () {
 2         $("#btnGenerate").click(function () {
 3             $.post("/GenerateTable/GetStus", "", function (result) {
 4                 if (result != null) {
 5                     $.each(result, function (index,value) {
 6                             var tmp = value;
 7                             var html = $("#moban").html();
 8                             html=html.replace(/{Name}/g, value.Name);
 9                             html=html.replace(/{Age}/g, value.Age);
10                             html=html.replace(/{City}/g, value.City);
11                             $("#destTable").append(html);
12                     });
13                 }
14             });
15         });
16     });

代码结构应该还算比较清晰,已经是早上5点了,就不展开讲了,效果如图:

posted @ 2015-08-09 05:09  SharpL  阅读(2006)  评论(0编辑  收藏  举报