2010-11-23 162 views
0

我目前有一堆方法在我的控制器從錶行中選擇記錄。ASP.NET MVC將映射對象數組傳遞給控制器​​參數從jQuery

,所以我可能有類似

var ids = []; 
var prices = []; 
var customers = []; 

$selectedRow.each(function() { 
    ids.push($(this).find('.id').text()); 
    prices.push($(this).find('.price').text()); 
    customers.push($(this).find('.customer').text()); 
}); 

$.post(....) // AJAX call to controller method 

和Controller我結束了

public ActionResult DoSomething(int[] ids, double[] prices, string[] customers) { ... } 

這僅僅是一個有點亂來處理使用迭代器。

我真正喜歡的是有

Class Foo 
{ 
    int id; 
    double price; 
    string customer; 
} 

,並能夠接收

public ActionResult DoSomething(List<Foo> foos) { ... } 

這可能嗎?

回答

3

有點哈克來幫助你,但這裏有一個例子:

// query array: construct this as usual 
var array = [{ id: '1', name: 'name 1' }, { id: '2', name: 'name 2'}]; 

// map the array into an array of DOM hidden fields 
var query = $.map(array, function (element, index) { 
    return [$(document.createElement('input')) 
        .attr('type', 'hidden') 
        .attr('name', 'foos[' + index + '].id') 
        .val(element.id), 
       $(document.createElement('input')) 
        .attr('type', 'hidden') 
        .attr('name', 'foos[' + index + '].name') 
        .val(element.name) 
       ]; 
}); 

// construct a form 
var form = $(document.createElement('form')); 
$(query).appendTo(form); 

$.ajax({ 
    url: '<%: Url.Action("Test") %>', 
    data: form.serialize(), 
    dataType: 'json', 
    success: function (result) { 
     alert('success'); 
    } 
}); 

這將成功地綁定到窗體的控制器動作:

public ActionResult Test(IEnumerable<Foo> foos) 
{ 
    ...  
} 

其中foo:

public class Foo 
{ 
    public string Id { get; set; } 
    public string Name { get; set; } 
} 

備註:所有這一切都沒有必要,如果你configure your controller action to accept JSON。在ASP.NET MVC 3中,它自動包含在框架中。

0
+0

雖然我沒有嘗試將模型綁定到表單,但這些解決方案不會與jQuery提交的值一起工作嗎? – fearofawhackplanet 2010-11-23 16:49:02

+0

是的,如果你使用`(「#form」)。serialize()`時提交表單本身 – Lorenzo 2010-11-23 16:51:12

0

菲爾哈克寫了這一篇博客文章太:Model Binding To A List

此外,MVC 3的模型活頁夾將支持J SON後的數據,我認爲 - 但這顯然不是今天要去:(

0

在我的情況下,視圖沒有被返回。它顯示在回調中的警報

相關問題