如何動態產生欄位和 ASP.Net MVC 資料繫結
前言
工作上遇到一個需求是動態產生欄位,並且可以正確接收到資料。動態產生欄位部分,有很多種方式,我採用了 jQuery Templates 來完成這需求,至於接收資料部分只需要利用 ASP.Net MVC 的資料繫結方式就可以幫我們轉成我們要的資料型態,可以讓後續處理上更加容易囉。
實作
首先定義我們的 Model:
1 2 3 4 5 |
public class SchoolData { public string SchoolName { set; get; } public string Department { set; get; } } |
接下來是 Controller 中要接收資料的 Action:
1 2 3 4 5 |
[HttpPost] public ActionResult SchoolList(List<SchoolData> SchoolDatas) { return View(SchoolDatas); } |
最後就是 View 的設計,因為我們用到了 jQuery Templates 這一個 Plugin ,這是由微軟為 jQuery 所開發的一個 Plugin 之前曾有傳言會直接放到 jQuery 裡面,但是最新版的似乎並還沒有打算放進去,因此我們得掛上 Plugin 的 js 檔案,而微軟也有提供 CDN 方便我們來引用:
http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js
微軟提供了兩個,一個是有精簡過的 min 版,看個人喜好自行引用囉!因為之後也會用到 Ajax,所以也順便掛上 Ajax 用的 js 檔案,最後也別忘記掛上 jQuery 的 js 檔案喔!
1 2 3 4 |
<script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script> <script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> |
接下來先設計我們要動態產生的欄位樣版,其中 ${index} 是未來我們要用資料來取代的部份,名稱設定為 index,此外還有一個隱藏欄位名稱為 SchoolDatas.index,SchoolDatas 是我們前面 Action 所接收的參數名稱,而值則是對應到後面 SchoolData[${index}],如果沒有此隱藏欄位的話,要接收的欄位名稱可以使用連續的數字來處理,[0].SchoolName、[1].SchoolName...依此類推,但是我還設計了一個移除按鈕,可能會導致移除後編號不連續,這樣在接收資料的時候就會接收不完全了,所以還是採用設定索引的方式來處理,而 SchoolName 和 DepartName 就是我們在 Model 所設計的欄位。
1 2 3 4 5 6 7 8 |
<div id="Template" style="display: none;"> <div id="School_${index}"> <input type="hidden" name="SchoolDatas.index" value="${index}" /> 學校:<input type="text" name="SchoolDatas[${index}].SchoolName" /><br /> 科系:<input type="text" name="SchoolDatas[${index}].Department" /> <input type="button" value="刪除" onclick="Remove('${index}')" /><br /> </div> </div> |
再來則是表單的部份:
1 2 3 4 5 6 7 8 9 |
<div> <%using (Ajax.BeginForm("SchoolList", new AjaxOptions() { UpdateTargetId = "Result" })) { %> <input type="button" value="新增" onclick="Add();" /> <input type="submit" value="送出" /> <div id="SchoolList"> </div> <%} %> </div> |
最後就是 jQuery 的程式:
1 2 3 4 5 6 7 8 9 10 11 12 |
<script type="text/javascript"> // 將 DIV 內容先轉成 template var schoolTemplate = $("#Template").template(); function Add() { $.tmpl(schoolTemplate, { index: new Date().getTime() }).appendTo("#SchoolList"); } function Remove(id) { $("#School_" + id).remove(); } </script> |
如此一來就大功告成囉!
▲表單送出結果
後記
ASP.Net MVC 在資料繫結上處理的很好,也為我們考慮到很多的情形,當我們表單有多選的欄位時候都可以幫我們轉換成 ICollection 型別,配合自定的 Model 類別,或是 Linq to SQL 更是可以讓我們可以快速的開發出我們要的系統,
範例下載:下載
三月 20th, 2011 - 22:14
讚喔
十一月 21st, 2011 - 22:36
謝謝