CheckBox and MVCCheckBox in MVC
I. Single Checkbox
1. View File
<% = Html. CheckBoxFor (model => model. IsNeverExpired) %>
2. The generated HTML is
<Input id = "IsNeverExpired" name = "IsNeverExpired" type = "checkbox" value = "true"/>
<Input name = "IsNeverExpired" type = "hidden" value = "false"/>
3. Remarks
(1) The HTML generated above is a bit strange. Why does it generate two controls?
If only one input is generated, the system cannot distinguish "No checkbox selected" from "no checkbox generated ".
(2) Why is it impossible to differentiate only one input?
When a form contains checkbox, if it is not assigned (selected), the value obtained in Request. Form on the server side is NULL.
2. Multiple checkboxes
Method 1: encoding the view page
C # code Replication
@ Using MvcCheckBoxList. Model @ model MvcApplication2.Models. UserVm @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. Cshtml ";}@ using (Html. beginForm () {@ Html. hiddenFor (m => m. user. id) <br/> @ Html. labelFor (m => m. user. name) @ Html. editorFor (m => m. user. name) @ Html. validationMessageFor (m => m. user. name) <br/> <ul style = "list-style: none;"> @ foreach (var a in Model. allRoles) {<li> @ if (Model. selectedRoleIds. contains (. id) {<input type = "checkbox" name = "SelectedRoleIds" value = "@. id "id =" @. id "checked =" checked "/> <Label for = "@. id "> @. name </label>} else {<input type = "checkbox" name = "SelectedRoleIds" value = "@. id "id =" @. id "/> <label for =" @. id "> @. name </label >}</li >}</ul> <br/> <input type = "submit" value = "set role for user"/>}@ section scripts {@ Scripts. render ("~ /Bundles/jqueryval ")}
Method 2: Expand through MvcCheckBoxList of NuGet
→ Tool -- library package manager -- package Manager Console → install-package MvcCheckBoxList
C # code Replication
@ Using MvcCheckBoxList. Model @ model MvcApplication2.Models. UserVm @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. Cshtml ";}@ using (Html. beginForm () {@ Html. hiddenFor (m => m. user. id) <br/> @ Html. labelFor (m => m. user. name) @ Html. editorFor (m => m. user. name) @ Html. validationMessageFor (m => m. user. name) <br/> @ Html. checkBoxListFor (m => m. selectedRoleIds, m => m. allRoles, // all roles r => r. id, // value r => r. name, // display value r => r. userRoles, // the Position of the current user role. horizontal // CheckboxList) <br/> <input type = "submit" value = "Set roles for users"/>}@ section scripts {@ Scripts. Render ("~ /Bundles/jqueryval ")}
In MVC3, how does one make the CheckBox button in the check box unavailable?
Add readonly or disable to the control.
Net mvc
Congratulations! It's late .........