[ASP.NET MVC] @Html.Label() 、@Html.LabelFor() 和 <label>

<input> 常常搭配 <label> 方便點選,產生的方法是 @Html.Label(),一個引數的寫法如下:

  @Html.Label("帳號:")

  // 會產生:

  <label for="帳號:">帳號:<label>

但是上面的結果通常不是我們要的,for 屬性要填別的 <input> 的 id ,常常是變數,這就要用兩個引數:

  @Html.Label("txtAccount"      // 成為 for,填的是點選後會 focus 到的目標 id
                , "帳號:")      // 成為 textContent ,顯示的文字內容

  // 會產生:

  <label for="txtAccount">帳號:<label>

也可用第三個引數帶入 HTML 屬性,使用匿名類別 new { } :

  @Html.Label("txtAccount":
                , "帳號:"
                , new { @class = "label-title" } )

  // 會產生:

  <label class="label-title" for="txtAccount">帳號:<label>

以上因為 class 是保留字所以前面要加上 @ 。另外有繫結 Model 時可用強型別的方法,例如這是從 Controller 帶往 View 的 ViewModel:

  public class VMLogin
  {
    public string Account { get; set; }
    public string Password { get; set; }
  }
  VMLogin vModel = new VMLogin();
  return View(vModel);

而 View 中可用 LabelFor() 快速產生並繫結:

  @model prjMvc.ViewModels.VMLogin

  @Html.LabelFor(m => m.Account
                  , "帳號:")
  @Html.TextBoxFor(m => m.Account)

  // 會產生:

  <label for="Account">帳號:</label>
  <input id="Account" name="Account" type="text" value="" />

也可在第三個引數帶入 HTML 屬性,增加樣式或事件:

  @model prjMvc.ViewModels.VMLogin

  @Html.LabelFor(m => m.Account
                  , "帳號:"
                  , new { onmouseover = "changeBgColor()" } )

  // 會產生:

  <label for="Account" onmouseover="changeBgColor()">帳號:</label>

如果在 Model 或 ViewModel 中已經有設定好 Annotation,可以更簡潔:

  using System.ComponentModel;      // 要引用命名空間
  ..
  ..
  public class VMLogin
  {
    [DisplayName("帳號")]           // 屬性 Account 要顯示的文字
    public string Account { get; set; }
    
    [DisplayName("密碼")]           // 屬性 Password 要顯示的文字
    public string Password { get; set; }
  }

在類別中的屬性上一行放上 DisplayName() 的 Attribute,這樣 @Html.LabelFor() 只要 lambda expression 的引數即可:

  @model prjMvc.ViewModels.VMLogin

  @Html.LabelFor(m => m.Account)
  @Html.LabelFor(m => m.Password)

  // 會產生:

  <label for="Account">帳號</label>
  <label for="Password">密碼>/label>

但寫什麼就呈現什麼,例如上面是「帳號」,不像前面手動寫的有冒號「帳號:」。

留言