.NET MVC3使用CheckBox List(复选框列表)的简单方法
MVC3中并沒有提供CheckBox List的實(shí)現(xiàn),剛開始用起來感覺很不方便,最初想到的是做HTMLHelpper的一些擴(kuò)展,但是那樣用起來感覺不是十分方便,并且需要在C#代碼里面寫HTML Style等一些東西。其實(shí),直接在View里面加一個(gè)循環(huán)就可以使用。
假如我做一個(gè)用戶添加功能,用戶可能屬于不同的角色:
?
?我定義Model的是 AddUserModel,里面有一個(gè)屬性Roles用來存放角色:
[Display(Name = "所屬角色")]public IEnumerable<SelectListItem> Roles { get; set; }
在Controller里面這樣寫:
public ActionResult AddUser(){
AddUserModel model = new AddUserModel();
InitMenu(model, AddUserModel.ITEM_ADD_USER);
var roles = new[]
{
new SelectListItem { Value = "1", Text="角色1", Selected = false },
new SelectListItem { Value = "2", Text="角色2",Selected = true },
new SelectListItem { Value = "3", Text="角色3",Selected = false },
};
model.Roles = roles;
return View(model);
}
[HttpPost]
public ActionResult AddUser(AddUserModel model, string[] roles)
{
InitMenu(model, AddUserModel.ITEM_ADD_USER);
return View(model);
}
?
視圖里面這樣寫:
<div class="editor-label">@Html.LabelFor(m => m.Roles)
</div>
<div class="editor-field">
@foreach (SelectListItem item in Model.Roles)
{
var ischecked = "";
if (item.Selected)
{
ischecked = "checked='checked'";
}
<input name="roles" type="checkbox" value="@item.Value" @ischecked />
@item.Text
}
</div>
?
這樣就可以實(shí)現(xiàn)一個(gè)CheckBox List了,通過修改視圖代碼可以自由定義樣式。Controller里面接收到的數(shù)據(jù)是這個(gè)樣子:
?
現(xiàn)在有一個(gè)問題就是每次在View里面使用CheckBox List的時(shí)候代碼有點(diǎn)點(diǎn)多,可以把現(xiàn)實(shí)代碼放在一個(gè)Template里面,比如Template的名字為CheckBoxList.cshtml:
Template 的代碼:
View Code @model IEnumerable<SelectListItem>@foreach (SelectListItem item in Model)
{
var ischecked = "";
if (item.Selected)
{
ischecked = "checked='checked'";
}
<input name="@ViewData["ListName"]" type="checkbox" value="@item.Value" @ischecked />
@item.Text
}
視圖里面的調(diào)用代碼:
<div class="editor-field">@Html.DisplayFor(m => m.Roles, "CheckBoxList", new {ListName="Roles"})
</div>
?這樣用起來就比較方便了。
轉(zhuǎn)載于:https://www.cnblogs.com/idlewater/archive/2011/12/06/2277814.html
總結(jié)
以上是生活随笔為你收集整理的.NET MVC3使用CheckBox List(复选框列表)的简单方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 炉石传说酒馆战棋比斯巨兽怎么样?比斯巨兽
- 下一篇: asp.net ajax控件工具集 Au