在我的应用程序 ASP.NET Core 中,我将一个复选框列表传递到我的 View 。
在我看来,我制作了一个 JavaScript 函数来选择所有复选框和取消选择所有复选框。
当我的复选框被选中时,我会发送表单。但在我的 Controller 中,任何复选框都被选中。
感谢您的帮助。
Javascript函数
function selectAllCompta() {
var items = document.getElementsByName('myCheckBox');
var cb = document.getElementById('cbSelectAll');
var txt = document.getElementById('txtCb');
if (cb.checked) {
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox')
items[i].checked = true;
}
txt.textContent = 'Déselectionner tout';
}
else {
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox')
items[i].checked = false;
}
txt.textContent = 'Sélectionner tout';
}
}
查看.cshtml
<input class="form-control" type="checkbox" id="cbSelectAll"
onclick='selectAllCompta()' />
<h4 id="txtCb">Sélectionner tout</h4>
<input asp-for="CBC[i].Selected" name="myCheckBox" type="checkbox"
class="form-control" />
最佳答案
由于我不知道您的 View 模型也不知道 html 标记,因此以下代码供您引用:
型号:
public class MyViewModel
{
public List<Item> CBC { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
Html 标记:
<form asp-action="GetValue" asp-controller="Home" method="post">
<input class="form-control" type="checkbox" id="cbSelectAll"
onclick='selectAllCompta()' />
<h4 id="txtCb">Sélectionner tout</h4>
<ul>
@for (var i = 0; i < Model.CBC.Count; i++)
{
<li>
<input type="checkbox" asp-for="@Model.CBC[i].Selected" />
<label asp-for="@Model.CBC[i].Selected">@Model.CBC[i].Name</label>
<input type="hidden" asp-for="@Model.CBC[i].Id" />
<input type="hidden" asp-for="@Model.CBC[i].Name" />
</li>
}
</ul>
<button type="submit" name="submit">submit</button>
</form>
@section Scripts {
<script>
function selectAllCompta() {
if ($("#cbSelectAll").is(":checked")) {
$("ul input[type='checkbox']").prop('checked', true);
$("#txtCb").val("Déselectionner tout");
}
else {
$("ul input[type='checkbox']").prop('checked', false);
$("#txtCb").val("Sélectionner tout");
}
}
</script>
}
这样在使用提交按钮发布到服务器端后,您将获得值:
public IActionResult GetValue(MyViewModel myViewModel) {
....
}
关于javascript - 在复选框列表上启用 js ASP.NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56562187/