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

Chọn option mặc định trong Razor Html.DropDownListFor() khi load trang

Trong ASP.NET MVC Razor, @Html.DropDownListFor() tự động chọn option khớp với giá trị của property trong Model. Cách ngắn gọn nhất là dùng SelectListItem với thuộc tính Selected.

Cú pháp ngắn gọn (Inline List)

@Html.DropDownListFor(
  m => m.Valeur, 
  new List<SelectListItem> {
    new SelectListItem { Value = "0", Text = "Hiển thị", Selected = Model.Valeur == 0 },
    new SelectListItem { Value = "1", Text = "Ẩn", Selected = Model.Valeur != 0 }
  }, 
  new { @class = "selectnew" }
)

Cách tốt hơn: ViewBag/ViewData + SelectList (Tách biệt logic)

Controller:

public ActionResult Edit(int id) {
  var model = _repo.Get(id);
  
  // Chuẩn bị SelectList trong ViewBag
  ViewBag.StatusOptions = new SelectList(new[] {
    new { Value = "0", Text = "Hiển thị" },
    new { Value = "1", Text = "Ẩn" }
  }, "Value", "Text", model.Valeur); // selectedValue = model.Valeur
  
  return View(model);
}

View:

@Html.DropDownListFor(
  m => m.Valeur, 
  (IEnumerable<SelectListItem>)ViewBag.StatusOptions, 
  "Chọn trạng thái", // Option label (rỗng)
  new { @class = "form-control selectnew" }
)

Cách dùng Enum (Type-safe)

public enum DisplayStatus { Show = 0, Hide = 1 }

public class MyModel {
  public DisplayStatus Valeur { get; set; }
}

// Controller
ViewBag.StatusOptions = new SelectList(Enum.GetValues(typeof(DisplayStatus)))
    .Cast<DisplayStatus>()
    .Select(e => new SelectListItem { 
      Value = ((int)e).ToString(), 
      Text = e.ToString(), 
      Selected = e == model.Valeur 
    });

// View
@Html.DropDownListFor(m => m.Valeur, ViewBag.StatusOptions, new { @class = "form-control" })

HTML kết quả sinh ra

<select class="selectnew" id="Valeur" name="Valeur">
  <option value="0" selected="selected">Hiển thị</option>
  <option value="1">Ẩn</option>
</select>

Lưu ý quan trọng

  • Model binding ưu tiên: Model.Value > Selected trong SelectListItem > selectedValue trong SelectList constructor.
  • Nếu Model.Valeur = null và không có option selected → option đầu tiên được chọn (hoặc option label).
  • Dùng new { @class = "..." } cho htmlAttributes (prefix @ vì class là từ khóa C#).
  • DropDownListFor sinh id và name từ expression (m => m.Valeur).

ASP.NET Core Tag Helper (Hiện đại hơn)

<select asp-for="Valeur" asp-items="ViewBag.StatusOptions" class="form-control">
  <option value="">Chọn trạng thái</option>
</select>