如何从视图向控制器发送所选复选框的列表

时间:2012-12-04 03:49:39

标签: html asp.net-mvc

我一直在努力弄清楚如何使用ActionLink获取所选复选框的列表。我想我需要使用JavaScript做一些客户端但无法找到相关代码。

以下代码使用提交按钮完美运行,将选定的ID作为id的数组回发,但我需要在包含其他按钮的页面上进行此操作。

// the view 
@foreach (var station in Stations)
{
   <input type="checkbox" name="selected" value="@station.StationId" /> 
}    
<input type="submit" value="Save" />

//Controller stub
public ActionResult Action(string [] selected) 

我被困在这几个小时,所以也许我看错了方法。

PS。经过几个小时的阅读和学习后,我的第一篇文章。

2 个答案:

答案 0 :(得分:4)

SomeButtons或发布复选框列表值的链接

<a href="#" id="someButton">Post</a>
//or buttons, helpers and any elements to trigger ajax post...

<强>的CheckBoxList:

<div id="MyDiv">
    @foreach (var station in Stations)
    {
        <input type="checkbox" name="selected" value="@station.StationId" /> 
    }  
</div>

<强>脚本:

$(document).ready(function() {
    $('#someButton').click(function() {
        var list = [];
        $('#MyDiv input:checked').each(function() {
            list.push(this.name);
        });
        // now names contains all of the names of checked checkboxes
        // do something with it for excamle post with ajax
        $.ajax({
            url: '@Url.Action("Action","Contoller")',
            type: 'POST',
            data: { Parameters: list},
            success: function (result) {
                alert("success")!
            },
            error: function (result) {
                alert("error!");
            }
        });   //end ajax
    });
});

<强>控制器:

public ActionResult Action(string [] Parameters) 

如果我做对了:)

答案 1 :(得分:3)

看起来你不是在寻找AJAX帖子。解决这个问题的最简单方法是将其包装在表单中并调用submit函数。以下是您的代码应该是什么样的:

@using(Html.BeginForm("uraction", "urcontroller", FormMethod.Post, new { id = "formId" })) { 
    foreach(var station in Stations) {
        <input type="checkbox" name="selected" value="@station.StationId" /> 
    }
}
<a href="#" id="postBtn">Post</a>
<script>
    $(document).ready(function() {
        $('#postBtn').click(function() {
            $('#formId').submit();
        }
    }
</script>
相关问题