SelectTagHelper : 是對HTML原生 tag的封裝
預設下拉選單會透過asp-for來設置select元素的模型屬性名稱,asp-items指定option元素。
新增好一個SelectController.cs跟相應Index檢視
SelectController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Net5App6.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Net5App6.Controllers
{
public class SelectController : Controller
{
[HttpGet]
public IActionResult Index()
{
SelectViewModel model = new SelectViewModel();
model.SelectLists = new List<SelectListItem>()
{
new SelectListItem() { Text="臺北市",Value="Taipei"},
new SelectListItem(){ Text="高雄市",Value="Kaohsiung",Selected=true},
new SelectListItem(){ Text="新竹市",Value="Hsinchu"}
};
return View(model);
}
[HttpPost]
public IActionResult Index(SelectViewModel model)
{
var name = model.City;
return View(model);
}
}
}
Index.cshtml
@model SelectViewModel
<form method="post">
<div>
<label asp-for="City"></label>
<select asp-for="City" asp-items="Model.SelectLists"></select>
</div>
<div>
<input type="submit" value="提交" />
</div>
</form>
對應檢視模型 SelectViewModel
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Net5App6.Models
{
public class SelectViewModel
{
[Display(Name = "直轄市")]
public string City { get; set; }
public List<SelectListItem> SelectLists { get; set; }
}
}
運行效果
預設asp-items我們透過 Model.SelectLists即可將所有集合中選項都綁定到option中。
而若我們想要去設置預設被選中的選項
法1.SelectListItem當中的屬性Selected設置為true
法2.藉由設置屬性為特定value的值
本篇同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/08/net-core19selecttaghelper.html