[ASP.NET MVC] @Html.Hidden() 、@Html.HiddenFor() 和 <input type="hidden">
有時候傳輸 form data 有一種需求,就是有資料需要靠 name 繫結然後傳到後端做處理,但又不想讓使用者看到,這時就常常使用 <input type="hidden"> ,例如商品 ID 會在 View 放在 <input type="hidden" name="productId" value="ab0123456"> 或類似的應用。而產生這樣的標籤可以使用 @Html.Hidden() 方法,一個引數時表示 id 和 name:
@Html.Hidden("productId") // 會產生: <input id="productId" name="productId" type="hidden" value="" />
若要馬上將值帶入 value,使用第二個引數:
@Html.Hidden("productId" , "ab0123456") // 會產生: <input id="productId" name="productId" type="hidden" value="ab0123456" />
三個引數時可帶入 HTML Attribute 增加樣式或事件,要使用匿名類別(但好像沒什麼會這樣的需求):
@Html.Hidden("productId" , "ab0123456" , new { onchange = "checkValue()" } ) // 會產生: <input id="productId" name="productId" onchange="checkValue()" type="hidden" value="ab0123456" />
若有繫結 Model 可使用強型別的 HiddenFor(),例如類別 Product:
class Product { public string ProductId { get; set; } public string Name { get; set; } public int Price { get; set; } }
在 Controller 傳到 View:
Product prod = new Product{ ProductId = "ab0123456", Name = "鍵盤紅軸", Price = 2990 }; return View(prod);
在 View 中可快速產生給 ProductId 的 <input> :
@Html.HiddenFor(m => m.Product) // 可產生: <input id="ProductId" name="ProductId" type="hidden" value="ab0123456" />
開發時希望能傳遞某個值要使用 TextBox,但不想被修改,就使用 <input type="text" disabled /> ,但是 disabled 的控制項的 value 其實無法送到後端,會是 null ,所以 type="hidden" 其實是蠻常用的技巧呢。
- @Html.ActionLink() 和 <a>
- @Html.TextBox() 、@Html.TextBoxFor() 和 <input type="text">
- @Html.TextArea() 、@Html.TextAreaFor() 和 <textarea>
- @Html.Label() 、@Html.LabelFor() 和 <label>
- @Html.Password() 、@Html.PasswordFor() 和 <input type="password">
- @Html.RadioButton() 、@Html.RadioButtonFor() 和 <input type="radio">
- @Html.CheckBox() 、@HtmlCheckBoxFor() 和 <input type="checkbox">
- @Html.DropDownList() 、@Html.DropDownListFor() 和 <select> 與<option>
- @Html.BeginForm() 和 <form>
- @Html.Hidden() 、@Html.HiddenFor() 和 <input type="hidden">
- @Html.DisplayFor() 、@Html.DisplayTextFor()、@Html.DisplayNameFor() 和 @Html.EditorFor()
留言
張貼留言