Post checked checkboxes to controller action without using HTML helper like Html.CheckboxList

怎甘沉沦 提交于 2019-12-17 18:53:18

问题


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 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".....>);.

Every checkbox has its own 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?


回答1:


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>

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




回答2:


If you want generated html like

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



来源:https://stackoverflow.com/questions/25038736/post-checked-checkboxes-to-controller-action-without-using-html-helper-like-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!