.NET Core第17天_LabelTagHelper的使用

LabelTagHelper的使用
對應於HTML <label>  tag的封裝,用於給予<input>對應的顯示名稱。
<label>當中的for屬性會關聯於<input>的Id屬性值一致,使彼此關聯可以用TAB標註。



新增好一個LabelController跟相應Index檢視
LabelController.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Controllers
{
    public class LabelController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}


./Views/Label/Index.cshtml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@model LabelViewModel
<div>
    <label asp-for="Name"></label>
    <input type="text" asp-for="Name" />
</div>

<div>
    <label asp-for="Age"></label>
    <input type="text" asp-for="Age" />
</div>




新增LabelViewModel

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Models
{
    public class LabelViewModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}


預設顯示效果


這裡若想更改顯示中文可以去調整ViewModel上面透過Display的Data Annotation來做調整為中文顯示

LabelViewModel.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Net5App6.Models
{
    public class LabelViewModel
    {
        [Display(Name="姓名")]
        public string Name { get; set; }
        [Display(Name = "年齡")]
        public int Age { get; set; }
    }
}






留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題