You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断同一class(allchkbox)的复选框中哪些被选中?

How to Identify Checked Checkboxes with Class "allchkbox"

Alright, let's break down how you can figure out which of your allchkbox class checkboxes are checked, both on the client side and how to send that data to your ASP.NET server if needed.

Client-Side Check (JavaScript)

First, here's how to get the checked boxes using plain JavaScript—no libraries required:

// Grab all checkboxes with the 'allchkbox' class
const allCheckboxes = document.querySelectorAll('.allchkbox');

// Filter down to only the ones that are checked
const checkedBoxes = Array.from(allCheckboxes).filter(box => box.checked);

// Now you can do something with them, like log their values
checkedBoxes.forEach(box => {
    console.log(`Checked box value: ${box.value}`);
});

Quick note: Make sure each checkbox has a value attribute set (e.g., <input type="checkbox" class="allchkbox" value="@ac.Action_id" />). Without a value, you won't be able to tell which specific action/module was checked!

If you're using jQuery in your project, this is even simpler:

// Directly select all checked 'allchkbox' checkboxes
const checkedBoxes = $('.allchkbox:checked');

// Loop through them to access values
checkedBoxes.each(function() {
    console.log(`Checked box value: $(this).val()`);
});

Sending Checked Values to Your ASP.NET Server

Once you've identified the checked boxes, you'll probably want to send that data to your controller. Here are two common approaches:

1. Form Submission with Model Binding

Update your checkbox markup to bind to a list property in your view model. For example, if your view model has a List<int> SelectedActionIds property:

<input type="checkbox" class="allchkbox" name="SelectedActionIds" value="@ac.Action_id" />

Then, in your controller action, you can directly receive the list of selected IDs:

[HttpPost]
public IActionResult AssignPrivileges(List<int> SelectedActionIds)
{
    // SelectedActionIds will hold all the values from checked checkboxes
    // Do your processing here (save to database, etc.)
    return RedirectToAction("PrivilegesList");
}

2. Asynchronous AJAX Call

If you don't want to reload the page, use AJAX to send the data:

// Collect all checked values into an array
const selectedValues = Array.from(document.querySelectorAll('.allchkbox:checked'))
                          .map(box => box.value);

// Send the data via fetch API
fetch('/YourController/AssignPrivileges', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        // Don't forget the anti-forgery token to prevent CSRF attacks
        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
    },
    body: JSON.stringify(selectedValues)
})
.then(response => response.json())
.then(result => {
    // Handle success (e.g., show a confirmation message)
    console.log('Privileges updated:', result);
})
.catch(error => {
    console.error('Error updating privileges:', error);
});

And your controller action would look like this:

[HttpPost]
public IActionResult AssignPrivileges([FromBody] List<int> selectedValues)
{
    // Process the selected IDs here
    return Json(new { success = true, message = "Privileges assigned successfully" });
}

Important Reminder: Always include the anti-forgery token when submitting data to ASP.NET controllers—it's a critical security measure against cross-site request forgery attacks.

内容的提问来源于stack exchange,提问作者Shubham Agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:58:46