使用Ajax.ActionLink将值数组传递给Action

时间:2012-05-03 10:54:12

标签: asp.net-mvc jquery

我想为我的Action提供一个整数值数组(基于表单上选定的复选框值)。我正在尝试使用Ajax.ActionLink,如下所示......

    <%= Ajax.ActionLink("Submit", "PrintPinLetters", "EPOC", new { selectedItemsToPrint }, new AjaxOptions { HttpMethod="POST", UpdateTargetId = "PrintConfirmation", LoadingElementId = "resultLoadingDiv", OnFailure="handleError"}, new { id = "btnPrintPinLetter" }) %>                            

但不确定传递给routeValue部分的内容。我在控制器中的动作定义为......

    [HttpPost]
    public ActionResult PrintPinLetters(Int64[] selectedItemsToPrint)
    {                           

基本上我希望在'selectedItemsToPrint'中传递一个数组(或逗号分隔的ID值列表)。此列表将使用由表格的多行中的复选框(全部命名相同)定义的值构建。

我使用过Ajax.BeginForm,但由于这会导致嵌套表单,因此在使用旧版浏览器(IE 7和8)时会产生不可预测的结果。

1 个答案:

答案 0 :(得分:0)

通常我会用jQuery调用自己做ajax。你可以像这样设置它

  1. 而不是使用Ajax.ActionLink(),使用Html.ActionLink(.... {id =“myid”})。别忘了给你的链接一个id
  2. 创建一个onready函数

    $(document).ready(function () {
        $('#myid').click(function() {
            var allElements = $('#container').find('input').serialize();  
            $.post(action, allElements, function (data) {
                // add your code here to process the data returned from the post.
            });
    
            return false;  // dont post the form
        });
    });
    
  3. 不要忘记将所有输入元素的name属性设置为selectedItemsToPrint,以便绑定能够与您的actionresult一起正常工作

  4. Html应该看起来像这样

    <div id="container">
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue0" />
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue1" />
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue2" />
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue3" />
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue4" />
        <input type="checkbox" name="selectedItemsToPrint" value="somevalue5" />
    </div>