iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

.NET Core MVC網頁應用開發系列 第 19

.NET Core第19天_SelectTagHelper的使用

  • 分享至 

  • twitterImage
  •  

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; }
    }
}

運行效果
https://ithelp.ithome.com.tw/upload/images/20210919/20107452btdVNCtC82.png

https://ithelp.ithome.com.tw/upload/images/20210919/20107452nE6ZdJ1MF7.png

預設asp-items我們透過 Model.SelectLists即可將所有集合中選項都綁定到option中。

https://ithelp.ithome.com.tw/upload/images/20210919/20107452TSKpSttLBr.png

https://ithelp.ithome.com.tw/upload/images/20210919/20107452lcAGhsrTDV.png

而若我們想要去設置預設被選中的選項
法1.SelectListItem當中的屬性Selected設置為true

https://ithelp.ithome.com.tw/upload/images/20210919/20107452zOVc6civdo.png

法2.藉由設置屬性為特定value的值

https://ithelp.ithome.com.tw/upload/images/20210919/201074528TvwPFKKCQ.png

本篇同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/08/net-core19selecttaghelper.html


上一篇
.NET Core第18天_InputTagHelper的使用
下一篇
.NET Core第20天_TextAreaTagHelper的使用
系列文
.NET Core MVC網頁應用開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言