ASP.NET Core MVC 快速產生下拉式選單 示範

在 ASP.NET Core MVC 中要在 cshtml 中顯示下拉式選單,一般會使用 select 這個 HTML tag,然後增加一堆 option ,來設定選項,其實使用 HtmlHelper 中的 DropDownList 就可以很簡單的自動產生了

本文使用自訂類別集合和字串集合這 2 種作示範,先快速帶過基本程式碼

範例基本程式碼

建立自訂物件
    
public sealed record Dto(string Id, string Name);
    

測試資料:
    
    public List<Dto> Dtos = new()
    {
        new Dto("1", "無糖"),
        new Dto("2", "微糖"),
        new Dto("3", "半糖"),
        new Dto("4", "正常糖"),
        new Dto("5", "多糖"),
    };

    public List<string> Names = new()
    {
        "紅茶",
        "綠茶",
        "奶茶",
        "烏龍茶",
    };
    

將內容傳送到 cshtml 頁面
    
    public IActionResult Index()
    {
        ViewData[nameof(Dtos)] = Dtos;
        ViewData[nameof(Names)] = Names;
        return View();
    }
    

前端頁面接收資料:
    
@{
	List<Dto> dtos = ViewData["Dtos"] as List<Dto> ?? new List<Dto>();
	List<string> names = ViewData["Names"] as List<string> ?? new List<string>();
}
    

使用 DropDownList 快速產生下拉式選單

終於要進入正題了,首先看看最簡單的範例:

List<string>

    
@Html.DropDownList("id", new SelectList(names), "請選擇")
    

其中第一個參數 "id" 轉換為 html 後就是 id ,中間則是選項(option),而最後面則是預設值,確切的 html 為:
    
<select class="form-select" id="id" name="id">
	<option value="">請選擇</option>
	<option>紅茶</option>
	<option>綠茶</option>
	<option>奶茶</option>
	<option>烏龍茶</option>
</select>
    

List<自訂物件>

如果是自訂物件,只要使用 SelectList 指定值和顯示內容的屬性名稱即可:
    
	@Html.DropDownList("id", new SelectList(dtos, nameof(Dto.Id), nameof(Dto.Name)), "請選擇")
    

html:
    
<select id="id" name="id">
	<option value="">請選擇</option>
	<option value="1">無糖</option>
	<option value="2">微糖</option>
	<option value="3">半糖</option>
	<option value="4">正常糖</option>
	<option value="5">多糖</option>
</select>
    

加上 css

方便是方便,就是太醜了,該如何加上 class?
    
	@Html.DropDownList("id", new SelectList(dtos, nameof(Dto.Id), nameof(Dto.Name)), "請選擇", new { @class = "form-select" })
    

只要在最後面使用匿名類別即可,在 class 前面要加上 @ 是因為 class 剛好是保留字。

系結表單屬性

假設我們有個 ViewModel:
    
    public class ViewModel
    {
        public string DtoId { get; set; }
        public string Name { get; set; }
    }
    

在 cshtml 想要將下拉式選單選到的內容直接綁定到 ViewModel 中的屬性該怎麼做?
    
@model WebApplicationTest.Controllers.DataController.ViewModel
    
@Html.DropDownListFor( x => x.DtoId, new SelectList(dtos, nameof(Dto.Id), nameof(Dto.Name)), "請選擇")
    

只要將 DropDownList 換成 DropDownListFor ,並且在第一個參數中指向 ViewModel 的物件即可

DropDownListFor 設定預設值

只要將系結的欄位設定預設值即可,例如:
    
    public class ViewModel
    {
        public string DtoId { get; set; } = "1";
        public string Name { get; set; }
    }
    

留言