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

添加ID选择器后Razor复选框无法切换状态的问题及解决

问题:Razor复选框手动添加ID后无法切换状态

在使用Razor生成自定义样式复选框时,手动为<input>添加id="chkb"后,复选框被锁定为开启状态,无法点击切换。尚未接入jQuery,后台无报错,仅添加ID就出现该问题。

可用代码(未手动添加ID时正常)

<div class="custom-control custom-checkbox">
    <input class="custom-control-input" type="checkbox" asp-for="myReportModel.ReportType_PushReport">
    <label class="custom-control-label" asp-for="myReportModel.ReportType_PushReport"></label>
</div>

不可用代码(添加ID后锁定)

<div class="custom-control custom-checkbox">
    <input class="custom-control-input" type="checkbox" id="chkb" asp-for="myReportModel.ReportType_PushReport">
    <label class="custom-control-label" asp-for="myReportModel.ReportType_PushReport"></label>
</div>

解决方法:同步label的for属性与input的ID

自定义样式复选框(custom-control-checkbox)的交互依赖<label>的for属性与<input>的id关联。手动添加input的ID后,label的for属性未同步更新,导致点击label无法触发input的状态切换(原生input被自定义样式隐藏,用户实际点击的是label)。只需为label添加for="chkb",与input的ID对应即可恢复正常:

<div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" id="chkb" asp-for="myReportModel.chkParams.ReportType_PushReport" checked="@(Model.myReportModel.chkParams.ReportType_PushReport == true)">
    <label class="custom-control-label" asp-for="myReportModel.chkParams.ReportType_PushReport" for="chkb"></label>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:43:27