asp.net-mvc 将选中的复选框发布到控制器操作,而不使用像 Html.CheckboxList 这样的 HTML 助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25038736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Post checked checkboxes to controller action without using HTML helper like Html.CheckboxList
提问by user2614879
I have a list of items and I would like to delete items that are checked in a list of checkboxes.
我有一个项目列表,我想删除在复选框列表中选中的项目。
I can't use something like CheckboxListsince I'm using Grid.Mvcto display my lines. That is why I create checkboxes in each line with column.add("<input type="checkbox".....>);.
我不能使用类似的东西,CheckboxList因为我Grid.Mvc用来显示我的线条。这就是为什么我在每一行中创建复选框的原因column.add("<input type="checkbox".....>);。
Every checkbox has its own ID:
每个复选框都有自己的 ID:
<input type="checkbox" id="3">
<input type="checkbox" id="4">...
I would like to know how to pass all checked checkbox IDs to the controller (from there I will perform delete operations). How can I post an array of checked IDs from my form to my controller action with one button press?
我想知道如何将所有选中的复选框 ID 传递给控制器(从那里我将执行删除操作)。如何通过按一下按钮将一系列已检查的 ID 从我的表单发布到我的控制器操作?
回答by Jeremy Cook
Example of generated HTML:
生成的 HTML 示例:
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
...
<button type="submit">Submit</submit>
Controller action:
控制器动作:
[HttpPost]
public ActionResult MyAction(int[] deletedItems)
{
// deletedItems contains all values that were checked
// when the submit button was clicked. Here you can
// loop through the array of IDs and delete by ID.
...
}
Note that the checkboxes do not have an idattribute. It is not used for model binding. Instead it has a nameattribute named "deletedItems" that matches the name of the argument of the MyActioncontroller action, and that is what is used when model binding. The valueattribute of checked checkboxes will be used to populate the deletedItemsarray of int[].
请注意,复选框没有id属性。它不用于模型绑定。相反,它有一个name名为“deletedItems”的属性,它与MyAction控制器操作的参数名称相匹配,这就是模型绑定时使用的。所述value选中的复选框的属性将被用于填充deletedItems的阵列int[]。
回答by Jun Fan
If you want generated html like
如果你想要生成 html 就像
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
Then you can use the following code
然后你可以使用下面的代码
<td>@Html.CheckBox("selectedItems", new { @value = @item.checkId })</td>
<td><input id="selectedItems" name="selectedItems" type="checkbox" value="11503" />
<input name="selectedItems" type="hidden" value="false" />
</td>
It won't pass selectedItems to controller.
它不会将 selectedItems 传递给控制器。

