Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Khắc phục Materialize CSS checkbox không hoạt động với @Html.CheckBoxFor (ASP.NET MVC)

Vấn đề: Materialize CSS yêu cầu cấu trúc HTML cụ thể cho checkbox (input + label + span), nhưng @Html.CheckBoxFor() của ASP.NET MVC sinh ra 2 input (checkbox + hidden) làm vỡ cấu trúc → checkbox bị ẩn hoặc lệch vị trí.

Nguyên nhân

@Html.CheckBoxFor(m => m.IsActive) sinh ra:

<input type="checkbox" name="IsActive" value="true" />
<input type="hidden" name="IsActive" value="false" /> <!-- Hidden field gây lỗi layout -->

Materialize CSS selector input[type="checkbox"] + label không khớp do hidden input chen giữa.

Giải pháp 1: Di chuyển hidden input xuống cuối (jQuery)

<script>
$(document).ready(function() {
  // Di chuyển tất cả hidden input của checkbox ra khỏi đường
  $('input[type="checkbox"]').each(function() {
    var $hidden = $(this).next('input[type="hidden"][name="' + this.name + '"]');
    if ($hidden.length) {
      $hidden.appendTo($(this).parent()); // Move to end of parent
    }
  });
});
</script>

Giải pháp 2: Custom Editor Template (Khuyên dùng, sạch hơn)

Tạo file Views/Shared/EditorTemplates/Boolean.cshtml:

@model bool?
@{
  var htmlAttributes = new Dictionary<string, object>();
  htmlAttributes.Add("type", "checkbox");
  htmlAttributes.Add("class", "filled-in"); // Materialize class
  if (ViewData.ModelMetadata.IsRequired) htmlAttributes.Add("required", "required");
}

<div class="form-check">
  @Html.CheckBoxFor(m => m, htmlAttributes)
  @Html.LabelFor(m => m, new { @class = "form-check-label" })
  @Html.ValidationMessageFor(m => m)
</div>

Sau đó dùng bình thường: @Html.EditorFor(m => m.IsActive).

Giải pháp 3: Viết thủ công (Full control)

<div class="form-check">
  <input type="checkbox" id="IsActive" name="IsActive" class="filled-in" value="true" @(Model.IsActive ? "checked" : "") />
  <label for="IsActive">Kích hoạt</label>
  @* Hidden field để post back false khi unchecked *@
  <input type="hidden" name="IsActive" value="false" />
</div>

Materialize CSS Checkbox Structure (Tham khảo)

<!-- Filled-in style -->
<div class="form-check">
  <input type="checkbox" id="test1" class="filled-in" checked="checked" />
  <label for="test1">Filled-in checkbox</label>
</div>

<!-- Outlined style (default) -->
<div class="form-check">
  <input type="checkbox" id="test2" />
  <label for="test2">Outlined checkbox</label>
</div>

Lưu ý

  • Luôn đặt id cho input và for cho label trùng khớp.
  • Hidden input phải sau label (hoặc ngoài wrapper) để CSS selector hoạt động.
  • Khởi tạo Materialize: M.AutoInit() hoặc document.addEventListener('DOMContentLoaded', ...).