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
<<: Day 06 | Dart基本介绍 - private & static
天亮了 昨晚是平安夜 关於迷雾森林故事 粉红烟花三个月 由於黑洞把12只 animal 吸走後的烟 ...
暨昨天介绍了物体的基本建立,我们今天来到中篇,没错,中篇後面还会有一个下篇,因为笔者写着写着发现篇幅...
这里是大卫吴的铁人纪录 嘛~这是我第一次参赛 期许自己能完成30天的挑战 以下主题相关: 这次铁人的...
tags: 2021铁人赛 React 投资Dashboard内容设计 要实际动手制作wirefra...
接下来讲讲查询 部分... Controller public ActionResult Index...