2014-10-29 96 views
1

我有標識& Name屬性EMP類綁定jQuery的陣列到ASP.NET MVC模型

class Emp 
{ 
    int id{get;set;} 
    int Name{get;set;} 
} 

@model List<Emp> 
<script> 
    function convertJqueryModelToMVC() 
    { 
      var emps = []; 
      emps.push({id:1,Name:"abc"}); 
      emps.push({id:2,Name:"xyz"}); 
      //logic for converting emps to List<emp> model 
    } 
</script> 

我要做到這一點,這樣當我點擊提交按鈕,所有表單域將在提交單個回發。這只是我試圖實現的一個例子 (注意:我知道標準的MVC過程)

+0

使用的WebAPI了點。 – frenchie 2014-10-29 03:09:26

+0

我們在我們的項目中不使用WebAPI – Tuscan 2014-10-29 03:12:55

+0

您是否想動態地將值附加到您的表單然後將其提交給服務器端? – Rahul 2014-10-29 03:43:32

回答

1

從Javascript傳入Json對象,模型聯編程序會自動完成它的工作。喜歡這個。

var emps= [ 
     { id: 1, Name: 'name1' }, 
     { id: 2, Name: 'name2' }, 
     { id: 3, Name: 'name3' } 
    ];  

    emps= JSON.stringify({ 'empList': emps}); 

    $.ajax({ 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 
     type: 'POST', 
     url: '/Home/Employee', 
     data: emps, 
     success: function() {   
      $('#result').html('successfully called.'); 
     }, 
     failure: function (response) {   
      $('#result').html(response); 
     } 
    }); 

在你的控制器

public ActionResult Employee(List<Emp> empList) 
{ 

//Your Logic 

} 
+0

我不想做一個AJAX調用我想發送數據提交按鈕 – Tuscan 2014-10-29 07:35:56

+1

那麼爲什麼你在構建JavaScript數組在convertJqueryModelToMVC函數?如何在不使用Ajax的情況下將Javascript數組發送到控制器? – 2014-10-29 08:44:36

+0

我創建了名稱=「[0] .Id」&「[0] .Name」的動態隱藏字段,並且我在HttpPost中獲得了模型 – Tuscan 2014-10-29 18:18:11