.NET Core第19天_SelectTagHelper的使用
SelectTagHelper : 是對HTML原生<select> tag的封裝
預設下拉選單會透過asp-for來設置select元素的模型屬性名稱,asp-items指定option元素。
新增好一個SelectController.cs跟相應Index檢視
SelectController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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
1 2 3 4 5 6 7 8 9 10 11 | @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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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的值
留言
張貼留言