[ASP.NET MVC] @Html.CheckBox() 、@HtmlCheckBoxFor() 和 <input type="checkbox">
要產生勾選方塊的 <input type="checkbox">,使用 @Html.CheckBox(),一個引數時表示 id 和 name,如下:
@Html.CheckBox("isMarried")已婚 // 會產生: <input id="isMarried" name="isMarried" type="checkbox" value="true" /> <input name="isMarried" type="hidden" value="false" />已婚
會看到產生的 HTML 會有兩個,一個 @Html.CheckBox 會產生兩個 <input>,一個是 type="checkbox" 另一個是 type="hidden",畫面上是看不到 hidden 的,用意是在前端沒有勾選 checkbox 時,後端 form 會得到該 name 的 value 是 false,而前端勾選 checkbox 時後端會得到 true。
第二個引數是預設是否勾選的布林值,會增加 checked 屬性:
@Html.CheckBox("isMarried" , true)已婚 // 會產生: <input checked="checked" id="isMarried" name="isMarried" type="checkbox" value="true" /> <input name="isMarried" type="hidden" value="false" />已婚
可在第三個引數加上 HTML 屬性,例如樣式或事件:
@Html.CheckBox("isMarried" , true , new { onclick = "refreshGrid()" } )已婚 // 會產生: <input checked="checked" id="isMarried" name="isMarried" onclick="refreshGrid()" type="checkbox" value="true" /> <input name="isMarried" type="hidden" value="false" />已婚
還有強型別的做法,例如 Controller 有 Student 物件,有一個布林屬性:
Student studentA = new Student(); studentA.isPass = true; return View(studentA);
可在 View 中快速產生:
@model prjMvc.Models.Student @Html.CheckBoxFor(m => m.isPass)已婚 // 會產生 <input checked="checked" data-val="true" data-val-required="isPass 欄位是必要項。" id="isPass" name="isPass" type="checkbox" value="true" /> <input name="isPass" type="hidden" value="false" />已婚
- @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()
留言
張貼留言