代码之家  ›  专栏  ›  技术社区  ›  fearofawhackplanet

ASP.NET MVC从jquery向控制器参数传递映射对象数组

  •  0
  • fearofawhackplanet  · 技术社区  · 15 年前

    我目前在控制器中有许多方法,可以从表行中提取选定的记录。

    所以我可能会有

    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
    

    在控制器里我最终

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

    使用迭代器只是有点麻烦。

    我真正想要的是

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

    并且能够接收

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

    这有可能吗?

    4 回复  |  直到 14 年前
        1
  •  3
  •   Darin Dimitrov    15 年前

    有点老土,但这里有一个例子:

    // 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中,这将自动包含在框架中。

        3
  •  0
  •   Simon Bartlett    15 年前

    菲尔·哈克也写了一篇博客: Model Binding To A List

    此外,我认为MVC 3的模型绑定器将支持JSON Post数据,但这显然对您今天没有帮助:(

        4
  •  0
  •   Rohit Ramname    14 年前

    在我的例子中,视图没有被返回。它在回电中显示警报