本篇体验生成CheckBoxList的几个思路,扩展MVC的HtmlHelper生成CheckBoxList,并使之水平排开。
通过遍历从控制器方法拿到的Model集合
□ 思路
比如为一个用户设置角色
1、拿到角色集合实例放到ViewBag中。
2、把该用户当前的角色ID集合也放到ViewBag中。
3、前台视图遍历所有角色,如果当前用户的角色ID包含在用户当前的角色ID集合中,就让checkbox为选中。还可以设置每行的checkbox的数量,而遍历动态生成checkbox的name属性设置成"ckb_" + item.ID,以方便后台读取。
4、后台控制器读取新的角色ID集合,保存到数据库。
1、拿到角色集合实例放到ViewBag中。
var roles = RoleService.LoadEntities(lambda表达式).ToList();
ViewBag.Roles = roles;
2、把该用户当前的角色ID集合也放到ViewBag中。
var existingRoleIds = (from r in 某个Model.Role
select r.ID).ToList<int>();
ViewBag.OleRoleIDs = existingRoleIds;
3、前台视图遍历所有角色
1: List<int> roleIds = (List<int>)ViewBag.OleRoleIDs;
2: for(int i = 0; i < ((List)ViewBag.Roles).Count(); i++)
3: {
4: var item = ((List)ViewBag.Roles)[i];
5: string name = "ckb_" + item.ID; //checkbox的name属性
6: if(i != 0 && i % 3 ==0) //每行有3个checkbox
7: {
8:
9: }
10: if(roleIds.Contain(item.ID))
11: {
12:
13: "checkbox" checked="checked" id="@item.ID" name="@name" />
14:
15:
16: }
17: else
18: {
19:
20: "checkbox" id="@item.ID" name="@name" />
21:
22:
23: }
24: }
4、后台控制器读取新的角色ID集合,保存到数据库。
1: [HttpPost]
2: public ActionResult SomeActionMethod(FormCollection collection)
3: {
4: List<int> roleIds = new List<int>();
5: var temp = from key in collection.AllKeys
6: where key.Contains("ckb_")
7: select key;
8:
9: foreach(var item in temp)
10: {
11: if(Request.Form[item] == "on") //如果checkbox状态为被选中
12: {
13: roleIds.Add(int.Parse(item.Replace("ckb_","")));
14: }
15: }
16:
17: //TODO:调用服务层方法,删除原来所有的角色,添加新的角色
18: rreturn Content("ok");
19: }
通过扩展HtmlHelper方法
□ 有关城市的一个Model
1: namespace MvcCblist.Models
2: {
3: public class City
4: {
5: public int Sort { get; set; }
6: public string Name { get; set; }
7: }
8: }
□ 自定义一个CheckBoxListInfo,这个类型的集合实例传到视图,然后扩展方法根据这个类型的属性,把CheckBoxList渲染出来。
1: namespace MvcCblist.Models
2: {
3: public class CheckBoxListInfo
4: {
5: public string Value { get; private set; }
6: public string DisplayText { get; private set; }
7: public bool IsChecked { get; private set; }
8:
9: public CheckBoxListInfo(string value, string displayText, bool isChecked)
10: {
11: this.Value = value;
12: this.DisplayText = displayText;
13: this.IsChecked = IsChecked;
14: }
15: }
16: }
□ HomeController
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.Mvc;
6: using MvcCblist.Models;
7:
8: namespace MvcCblist.Controllers
9: {
10: public class HomeController : Controller
11: {
12: public ActionResult Index()
13: {
14: Listcities = new List ()
15: {
16: new City(){Sort = 1,Name = "济南市"},
17: new City(){Sort = 2,Name = "青岛市"},
18: new City(){Sort = 3,Name = "平度市"},
19: new City(){Sort = 4, Name = "即墨市"},
20: new City(){Sort = 5,Name = "威海市"},
21: new City(){Sort = 6,Name = "淄博市"},
22: new City(){Sort = 7, Name = "泰安市"}
23: };
24:
25: Listinfos = new List ();
26: foreach (City item in cities)
27: {
28: infos.Add(new CheckBoxListInfo(item.Sort.ToString(),string.Concat(item.Name,"-",item.Sort.ToString()),false));
29: }
30: ViewData["CheckBoxListOfCities"] = infos;
31: return View();
32: }
33:
34: }
35: }
36:
□ 自定义扩展方法
自定义扩展方法有3点需要注意:
1、命名空间用HtmlHelper一样的空间namespace System.Web.Mvc
2、静态类、静态方法
3、返回MvcHtmlString,就像其它内置帮助方法一样
1: using System.Collections.Generic;
2: using System.Text;
3: using System.Web.Routing;
4: using MvcCblist.Models;
5:
6: namespace System.Web.Mvc
7: {
8: public static class InputExtensions
9: {
10: //name对应input的属性name
11: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,
12: ListlistInfos, IDictionary<string, object> htmlAttributes)
13: {
14: if (string.IsNullOrEmpty(name))
15: {
16: throw new ArgumentException("此参数不能为空","name");
17: }
18: if (listInfos == null)
19: {
20: throw new ArgumentException("listInfos");
21: }
22: StringBuilder sb = new StringBuilder();
23: foreach (CheckBoxListInfo info in listInfos)
24: {
25: TagBuilder builder = new TagBuilder("input");
26: if (info.IsChecked)
27: {
28: builder.MergeAttribute("checked","checked");
29: }
30: builder.MergeAttributes(htmlAttributes);
31: builder.MergeAttribute("type", "checkbox");
32: builder.MergeAttribute("name",name);
33: builder.InnerHtml = info.DisplayText;
34: sb.Append(builder.ToString(TagRenderMode.Normal));
35: sb.Append("
");
36: }
37: return new MvcHtmlString(sb.ToString());
38: }
39:
40: //重载方法:不含属性键值对集合
41: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,
42: ListlistInfos)
43: {
44: return htmlHelper.CheckBoxList(name, listInfos, null);
45: }
46:
47: //重载方法:从路由中拿数据
48: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,
49: ListlistInfos, object htmlAttributes)
50: {
51: return htmlHelper.CheckBoxList(name, listInfos,
52: ((IDictionary<string, object>) new RouteValueDictionary(htmlAttributes)));
53: }
54: }
55: }
56:
□ Home/Index.cshtml视图
1: @using System.Web.UI.WebControls
2: @using MvcCblist.Models
3: @{
4: ViewBag.Title = "Index";
5: Layout = "~/Views/Shared/_Layout.cshtml";
6: }
7:
8:Index
9:
10: @Html.CheckBoxList("city", (List)ViewData["CheckBoxListOfCities"],null)
11:
这还不够,我们希望每行多显示几个checkbox。
完善扩展方法,使checkbox能水平排开,并可设置每行的个数
□ 考虑水平排开和每行显示个数的扩展方法
1: using System.Collections.Generic;
2: using System.Text;
3: using System.Web.Routing;
4: using MvcCblist.Models;
5:
6: namespace System.Web.Mvc
7: {
8: public static class InputExtensions
9: {
10: #region CheckBoxList
11: ///
12: /// CheckBoxList.
13: ///
14: /// The HTML helper.
15: /// The name.
16: /// CheckBoxListInfo.
17: ///
18: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, ListlistInfo)
19: {
20: return htmlHelper.CheckBoxList
21: (
22: name,
23: listInfo,
24: (IDictionary<string, object>)null,
25: 0
26: );
27: }
28: ///
29: /// CheckBoxList.
30: ///
31: /// The HTML helper.
32: /// The name.
33: /// CheckBoxListInfo.
34: /// The HTML attributes.
35: ///
36: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, ListlistInfo, object htmlAttributes)
37: {
38: return htmlHelper.CheckBoxList
39: (
40: name,
41: listInfo,
42: (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes),
43: 0
44: );
45: }
46: ///
47: /// CheckBoxList.
48: ///
49: /// The HTML helper.
50: /// The name.
51: /// The list info.
52: /// The HTML attributes.
53: ///
54: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, ListlistInfo, IDictionary<string, object> htmlAttributes)
55: {
56: if (String.IsNullOrEmpty(name))
57: {
58: throw new ArgumentException("必须给CheckBoxList一个Tag Name", "name");
59: }
60: if (listInfo == null)
61: {
62: throw new ArgumentNullException("必须要设置ListlistInfo" );
63: }
64: if (listInfo.Count < 1)
65: {
66: throw new ArgumentException("ListlistInfo 至少要一组资料" , "listInfo");
67: }
68: StringBuilder sb = new StringBuilder();
69: int lineNumber = 0;
70: foreach (CheckBoxListInfo info in listInfo)
71: {
72: lineNumber++;
73: TagBuilder builder = new TagBuilder("input");
74: if (info.IsChecked)
75: {
76: builder.MergeAttribute("checked", "checked");
77: }
78: builder.MergeAttributes<string, object>(htmlAttributes);
79: builder.MergeAttribute("type", "checkbox");
80: builder.MergeAttribute("value", info.Value);
81: builder.MergeAttribute("name", name);
82: builder.InnerHtml = string.Format(" {0} ", info.DisplayText);
83: sb.Append(builder.ToString(TagRenderMode.Normal));
84: sb.Append("");
85: }
86: return new MvcHtmlString(sb.ToString());
87: }
88: ///
89: /// CheckBoxList.
90: ///
91: /// The HTML helper.
92: /// The name.
93: /// The list info.
94: /// The HTML attributes.
95: /// The direction.
96: /// 每行的显示个数.
97: ///
98: public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, ListlistInfo, IDictionary<string, object> htmlAttributes, int number)
99: {
100: if (String.IsNullOrEmpty(name))
101: {
102: throw new ArgumentException("必须给这些CheckBoxList一个Tag Name", "name");
103: }
104: if (listInfo == null)
105: {
106: throw new ArgumentNullException("必须要设置ListlistInfo" );
107: }
108: if (listInfo.Count < 1)
109: {
110: throw new ArgumentException("ListlistInfo 至少要有一组资料" , "listInfo");
111: }
112: StringBuilder sb = new StringBuilder();
113: int lineNumber = 0;
114: foreach (CheckBoxListInfo info in listInfo)
115: {
116: lineNumber++;
117: TagBuilder builder = new TagBuilder("input");
118: if (info.IsChecked)
119: {
120: builder.MergeAttribute("checked", "checked");
121: }
122: builder.MergeAttributes<string, object>(htmlAttributes);
123: builder.MergeAttribute("type", "checkbox");
124: builder.MergeAttribute("value", info.Value);
125: builder.MergeAttribute("name", name);
126: builder.InnerHtml = string.Format(" {0} ", info.DisplayText);
127: sb.Append(builder.ToString(TagRenderMode.Normal));
128: if (number == 0)
129: {
130: sb.Append("
");
131: }
132: else if (lineNumber % number == 0)
133: {
134: sb.Append("
");
135: }
136: }
137: return new MvcHtmlString(sb.ToString());
138: }
139: #endregion
140: }
141: }
142:
□ Home/Index.cshtml视图
1: @using System.Web.UI.WebControls
2: @using MvcCblist.Models
3: @{
4: ViewBag.Title = "Index";
5: Layout = "~/Views/Shared/_Layout.cshtml";
6: }
7:
8:Index
9:
10: @Html.CheckBoxList("city", (List)ViewData["CheckBoxListOfCities"],null,3)
参考资料:
※ CheckBoxList Helper for MVC
※ Kevin Tseng