Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

asp.net mvc - Post checked checkboxes to controller action without using HTML helper like Html.CheckboxList

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...