ASP.NET MVC從視圖傳遞多個模型到Controller


從后台組織好數據然后傳遞到頁面倒是水到渠成很方便,因為MVC自身就將這樣的需求內建到了這個系統中。我只需要在后台組織好一個List 或IEnumerable類型的變量,將需要傳遞的數據模型扔進去便可。

 

比如這里我們向視圖返回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.調試看結果

 

結果顯示我們接收到了前台傳過來的每一個數據,完工。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM