標籤:
從後台組織好資料然後傳遞到頁面倒是水到渠成很方便,因為MVC自身就將這樣的需求內建到了這個系統中。我只需要在後台組織好一個List 或IEnumerable類型的變數,將需要傳遞的資料模型扔進去便可。
http://www.cnblogs.com/Wayou/p/pass_multi_modes_to_controller_in_MVC.html
比如這裡我們向視圖返回5條product資訊在頁面進行展示,僅僅是返回這麼簡單。
然後在頁面我們就毫不費力地得到了後台傳過來的資料模型,然後進行顯示即可。
但問題是,如何又將多個模型傳回後台去呢。一個form一般只傳遞一個模型,我們可以在JavaScript裡序列化多個模型然後通過ajax 傳遞迴去。
1.首先改造頁面,假設在頁面有很多輸入框供使用者輸入模型的相關資訊,並且搞一個按扭來提交。
<table> @foreach (Product item in Model) { <tr id="@item.ProductID"> <td> <input name="ProductName" /> </td> <td> <input name="SupplierID" /> </td> <td> <input name="CategoryID" /> </td> </tr> }</table><button id="go">Go</button>
2.然後在JavaScript中擷取這些輸入值,最後將所有模型整合到一個models變數中。
var models = []; $.each($("table tr"), function(i, item) { var ProductName = $(item).find("[name=ProductName]").val(); var SupplierID = $(item).find("[name=SupplierID]").val(); var CategoryID = $(item).find("[name=CategoryID]").val(); models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID }); });
當然這些是寫到按扭的單擊事件中的。
所以完整的代碼看起來應該是這個樣子。
<script type="text/javascript"> $("#go").click(function() { var models = []; $.each($("table tr"), function(i, item) { var ProductName = $(item).find("[name=ProductName]").val(); var SupplierID = $(item).find("[name=SupplierID]").val(); var CategoryID = $(item).find("[name=CategoryID]").val(); models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID }); }); });</script>
到這裡我們可以加個debugger測試一下有沒有有前台代碼中成功擷取到輸入框的值及組織好的模型對不對。
在頁面按F12開啟開發人員工具,然後試著在頁面輸入一些值,最後單擊按扭。
我們看到,在遍曆了所有輸入框後,以每行為單位當成一個Product模型,壓入models變數中。這個時候,models變數中儲存了所有資訊。
3.準備後台接收資料的Action 。我們當然是接收多個模型,所以接收類型選擇為List<Product>
public ActionResult ReceiveData(List<Product> products) { string result = products == null ? "Failed" : "Success"; return Content(result); }
4.最後一步,將models變數通過Ajax傳送到後台
這一步是最關鍵的,因為ajax格式沒寫好後台是無法接收到正確的資料的。經過我頗費心神的研究最後得出的ajax代碼大概是下面這個樣子的:
$.ajax({ url: ‘../../Home/ReceiveData‘, data: JSON.stringify(models), type: ‘POST‘, contentType: ‘application/json; charset=utf-8‘, success: function(msg) { alert(msg); } });
最後完整的前台代碼大概應該是這個樣子的。
<script type="text/javascript"> $(function() { $("#go").click(function() { var models = []; $.each($("table tr"), function(i, item) { var ProductName = $(item).find("[name=ProductName]").val(); var SupplierID = $(item).find("[name=SupplierID]").val(); var CategoryID = $(item).find("[name=CategoryID]").val(); models.push({ ProductName: ProductName, SupplierID: SupplierID, CategoryID: CategoryID }); }); $.ajax({ url: ‘../../Home/ReceiveData‘, data: JSON.stringify(models), type: ‘POST‘, contentType: ‘application/json; charset=utf-8‘, success: function(msg) { alert(msg); } }); }); })</script>
5.調試看結果
結果顯示我們接收到了前台傳過來的每一個資料,完工。
ASP.NET MVC從視圖傳遞多個模型到Controller