将选中的复选框发布到控制器操作,而不使用像 Html.CheckboxList 这样的 HTML 助手 [英] Post checked checkboxes to controller action without using HTML helper like Html.CheckboxList

查看:25
本文介绍了将选中的复选框发布到控制器操作,而不使用像 Html.CheckboxList 这样的 HTML 助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,我想删除在复选框列表中选中的项目.

I have a list of items and I would like to delete items that are checked in a list of checkboxes.

我不能使用 CheckboxList 之类的东西,因为我使用 Grid.Mvc 来显示我的行.这就是为什么我用 column.add("<input type="checkbox".....>); 在每一行中创建复选框的原因.

I can't use something like CheckboxList since I'm using Grid.Mvc to display my lines. That is why I create checkboxes in each line with column.add("<input type="checkbox".....>);.

每个复选框都有自己的 ID:

Every checkbox has its own ID:

<input type="checkbox" id="3">
<input type="checkbox" id="4">...

我想知道如何将所有选中的复选框 ID 传递给控制器​​(从那里我将执行删除操作).如何通过按一下按钮将一系列已检查的 ID 从我的表单发布到我的控制器操作?

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?

推荐答案

生成的 HTML 示例:

Example of generated 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>

控制器动作:

[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.
    ...
}

注意复选框没有 id 属性.它不用于模型绑定.相反,它有一个名为deletedItems"的 name 属性,该属性与 MyAction 控制器操作的参数名称相匹配,这就是模型绑定时使用的内容.选中复选框的 value 属性将用于填充 int[]deletedItems 数组.

Note that the checkboxes do not have an id attribute. It is not used for model binding. Instead it has a name attribute named "deletedItems" that matches the name of the argument of the MyAction controller action, and that is what is used when model binding. The value attribute of checked checkboxes will be used to populate the deletedItems array of int[].

这篇关于将选中的复选框发布到控制器操作,而不使用像 Html.CheckboxList 这样的 HTML 助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆