1、單個Checkboxhtml
一、View文件jquery
<%= Html.CheckBoxFor(model => model.IsNeverExpired)%>服務器
二、生成的HTML爲工具
<input id="IsNeverExpired" name="IsNeverExpired" type="checkbox" value="true" />
<input name="IsNeverExpired" type="hidden" value="false" />編碼
三、備註spa
(1)、上面生成的HTML有點奇怪, 爲何它會生成兩個控件呢?orm
由於若是隻生成一個input, 系統沒法區分"沒有選中checkbox" 和 "checkbox沒有生成".htm
(2)、那又是爲何只生成一個input就沒法區分呢?ip
原來當一個form中包含checkbox時,若是沒有給它賦值(選中), 在服務器端Request.Form中獲得的值是NULLinput
2、多個Checkbox
方法一:經過在視圖頁編碼的方式
@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(a.Id))
{
<input type="checkbox" name="SelectedRoleIds" value="@a.Id" id="@a.Id" checked="checked"/>
<label for="@a.Id">@a.Name</label>
}
else
{
<input type="checkbox" name="SelectedRoleIds" value="@a.Id" id="@a.Id" />
<label for="@a.Id">@a.Name</label>
}
</li>
}
</ul>
<br/>
<input type="submit" value="爲用戶設置角色"/>
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
} ![](http://static.javashuo.com/static/loading.gif)
方法二:經過NuGet的MvcCheckBoxList擴展
→工具--庫程序包管理器--程序包管理器控制檯→install-package MvcCheckBoxList
@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, //全部角色
r => r.Id, //value值
r => r.Name, //顯示值
r => r.UserRoles, //用戶當前角色
Position.Horizontal //CheckboxList排列方向
)
<br/>
<input type="submit" value="爲用戶設置角色"/>
}
@section scripts
{
@Scripts.Render("~/bundles/jqueryval")
} ![](http://static.javashuo.com/static/loading.gif)