2010-11-23 159 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

在我的情况下,视图没有被返回。它显示在回调中的警报

相关问题