ASP.NET MVC中如何按每日时间段启用禁用EditorFor控件
实现ASP.NET MVC EditorFor控件按时间段启用/禁用
服务器端渲染判断(页面加载时生效)
直接在视图里通过服务器当前时间判断区间,动态给控件添加禁用属性:
<div class="form-group"> @Html.LabelFor(model => model.TESTS_EVENING, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @{ var currentHour = DateTime.Now.Hour; // 判断是否在允许编辑的时间段内 var canEdit = currentHour >= 16 && currentHour <= 23; } @Html.EditorFor(model => model.TESTS_EVENING, new { htmlAttributes = new { @class = "form-control", // 不在时间段内就添加disabled属性 disabled = canEdit ? null : "disabled" } }) @Html.ValidationMessageFor(model => model.TESTS_EVENING, "", new { @class = "text-danger" }) </div> </div>
这种方式页面渲染完成后控件状态就固定了,适合不需要实时更新的场景,依赖服务器系统时间。
客户端实时判断(动态更新状态)
如果用户停留在页面期间,需要时间到点后自动切换控件状态,用JS实时检测:
<div class="form-group"> @Html.LabelFor(model => model.TESTS_EVENING, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.TESTS_EVENING, new { htmlAttributes = new { @class = "form-control evening-test-input" } }) @Html.ValidationMessageFor(model => model.TESTS_EVENING, "", new { @class = "text-danger" }) </div> </div> <script> // 检查时间并设置控件状态 function toggleEditStatus() { const now = new Date(); const hour = now.getHours(); const input = document.querySelector('.evening-test-input'); if (hour >= 16 && hour <= 23) { input.removeAttribute('disabled'); } else { input.setAttribute('disabled', 'disabled'); } } // 页面加载时初始化状态 toggleEditStatus(); // 每分钟检查一次,确保状态实时更新 setInterval(toggleEditStatus, 60000); </script>
这种方式依赖用户本地时间,适合需要实时响应时间变化的场景。如果要严格控制,建议提交表单时在服务器端再做一次时间校验,防止客户端篡改时间绕过限制。
内容的提问来源于stack exchange,提问作者Ziad Adnan
相关产品推荐
相关产品推荐

