[ASP.NET MVC] @Html.TextBox() 、@Html.TextBoxFor() 和 <input type="text">

<input>應該是最常用的獲得使用者資訊用的標籤了,@Html.TextBox() 使用如下,一個引數時為 id 和 name:

  @Html.TextBox("account")
  
  // 會產生:
  
  <input type="text" id="account" name="account" />
  

若要已填入特定字串,也就是 value 值,則放在第二個引數:

  @Html.TextBox("account"
               , "John123")
 
  // 會產生:

  <input type="text" id="account" name="account" value="John123" />

也可產生 HTML 屬性,要帶入 HTML Attribute 要用匿名類別 new { } 放在第三個引數:

  @Html.TextBox("account"
               , "John123"
               , new { required = true } )

  // 會產生:

  <input required="True" type="text" id="account" name="account" value="John123" />

以上會產生 reuiqred 屬性,在 form submit 時若為空,可在前端先行檢查,也可帶入 style 或不一樣的 id 或事件。另外有強型別的 TextBoxFor() 可以更快速給 Model 建立標籤,例如 Student 類別:

  class Student
  {
    public string Name { get; set; }
    public int Age { get; set; }
    public string Major { get; set; }
  }

Controller 中有 Student 物件,並將此 Model 帶往 View:

  Student newStudent = new Student();
  newStudent.Name = "Billy";     // 已給定 Name,則在 View 中會以 value 顯示
  return View(newStudent);

而 View 中綁定後,可用 For 的強型別寫法,第一個引數是 lambda expression 指定物件的哪一個屬性:

  @model prjMvc.Models.Student
  
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Age
                   , null
                   , new { type = "number"} )
  @Html.TextBoxFor(m => m.Major
                   , null
                   , new { placeholder = "請輸入主修" } )
                   
  // 會產生:
  
  <input type="text" id="Name" name="Name" value="Billy" />     // 屬性名自動繫結
  <input type="number" id="Age" name="Age" value="0" />
  <input type="text" id="Major" name="Major" placeholder="請輸入主修" value="" />

以上會看到每個 <input> 標籤的 id 和 name 都自動繫結了物件的屬性名,方便在 form submit 時自動綁定送出的屬性給 Model 或 ViewModel。

留言