MVC扩展生成CheckBoxList并水平排列

时间:2024-08-16 08:34:14

本篇体验生成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<Role>();
ViewBag.Roles = roles;

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

2、把该用户当前的角色ID集合也放到ViewBag中。

var existingRoleIds = (from r in 某个Model.Role
                    select r.ID).ToList<int>();
ViewBag.OleRoleIDs = existingRoleIds;

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

3、前台视图遍历所有角色

   1:  List<int> roleIds = (List<int>)ViewBag.OleRoleIDs;
   2:  for(int i = 0; i < ((List<Role>)ViewBag.Roles).Count(); i++)
   3:  {
   4:      var item = ((List<Role>)ViewBag.Roles)[i];
   5:      string name = "ckb_" + item.ID; //checkbox的name属性
   6:      if(i != 0 && i % 3 ==0) //每行有3个checkbox
   7:      {
   8:          <br />
   9:      }
  10:      if(roleIds.Contain(item.ID))
  11:      {
  12:          <span>
  13:              <input type="checkbox" checked="checked" id="@item.ID" name="@name" />
  14:              <label for="@item.ID">@item.RoleName</label>
  15:          </span>
  16:      }
  17:      else
  18:      {
  19:          <span>
  20:              <input type="checkbox" id="@item.ID" name="@name" />
  21:              <label for="@item.ID">@item.RoleName</label>
  22:          </span>
  23:      }
  24:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

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:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

  通过扩展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:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 自定义一个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:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 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:              List<City> cities = new List<City>()
  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:              List<CheckBoxListInfo> infos = new List<CheckBoxListInfo>();
  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:   

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

□ 自定义扩展方法

自定义扩展方法有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:              List<CheckBoxListInfo> listInfos, 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("<br />");
  36:              }
  37:              return new MvcHtmlString(sb.ToString());
  38:          }
  39:   
  40:          //重载方法:不含属性键值对集合
  41:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,
  42:              List<CheckBoxListInfo> listInfos)
  43:          {
  44:              return htmlHelper.CheckBoxList(name, listInfos, null);
  45:          }
  46:   
  47:          //重载方法:从路由中拿数据
  48:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,
  49:              List<CheckBoxListInfo> listInfos, object htmlAttributes)
  50:          {
  51:              return htmlHelper.CheckBoxList(name, listInfos,
  52:                  ((IDictionary<string, object>) new RouteValueDictionary(htmlAttributes)));
  53:          }
  54:      }
  55:  }
  56:   

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 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:  <h2>Index</h2>
   9:   
  10:  @Html.CheckBoxList("city", (List<CheckBoxListInfo>)ViewData["CheckBoxListOfCities"],null)
  11:   

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

效果:

MVC扩展生成CheckBoxList并水平排列

 

这还不够,我们希望每行多显示几个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:          /// <summary>
  12:          /// CheckBoxList.
  13:          /// </summary>
  14:          /// <param name="htmlHelper">The HTML helper.</param>
  15:          /// <param name="name">The name.</param>
  16:          /// <param name="listInfo">CheckBoxListInfo.</param>
  17:          /// <returns></returns>
  18:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo)
  19:          {
  20:              return htmlHelper.CheckBoxList
  21:              (
  22:                  name,
  23:                  listInfo,
  24:                  (IDictionary<string, object>)null,
  25:                  0
  26:              );
  27:          }
  28:          /// <summary>
  29:          /// CheckBoxList.
  30:          /// </summary>
  31:          /// <param name="htmlHelper">The HTML helper.</param>
  32:          /// <param name="name">The name.</param>
  33:          /// <param name="listInfo">CheckBoxListInfo.</param>
  34:          /// <param name="htmlAttributes">The HTML attributes.</param>
  35:          /// <returns></returns>
  36:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, object htmlAttributes)
  37:          {
  38:              return htmlHelper.CheckBoxList
  39:              (
  40:                  name,
  41:                  listInfo,
  42:                  (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes),
  43:                  0
  44:              );
  45:          }
  46:          /// <summary>
  47:          /// CheckBoxList.
  48:          /// </summary>
  49:          /// <param name="htmlHelper">The HTML helper.</param>
  50:          /// <param name="name">The name.</param>
  51:          /// <param name="listInfo">The list info.</param>
  52:          /// <param name="htmlAttributes">The HTML attributes.</param>
  53:          /// <returns></returns>
  54:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, 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("必须要设置List<CheckBoxListInfo> listInfo");
  63:              }
  64:              if (listInfo.Count < 1)
  65:              {
  66:                  throw new ArgumentException("List<CheckBoxListInfo> listInfo 至少要一组资料", "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("</br>");
  85:              }
  86:              return new MvcHtmlString(sb.ToString());
  87:          }
  88:          /// <summary>
  89:          /// CheckBoxList.
  90:          /// </summary>
  91:          /// <param name="htmlHelper">The HTML helper.</param>
  92:          /// <param name="name">The name.</param>
  93:          /// <param name="listInfo">The list info.</param>
  94:          /// <param name="htmlAttributes">The HTML attributes.</param>
  95:          /// <param name="direction">The direction.</param>
  96:          /// <param name="number">每行的显示个数.</param>
  97:          /// <returns></returns>
  98:          public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, 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("必须要设置List<CheckBoxListInfo> listInfo");
 107:              }
 108:              if (listInfo.Count < 1)
 109:              {
 110:                  throw new ArgumentException("List<CheckBoxListInfo> listInfo 至少要有一组资料", "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("<br />");
 131:                  }
 132:                  else if (lineNumber % number == 0)
 133:                  {
 134:                      sb.Append("<br />");
 135:                  }
 136:              }
 137:              return new MvcHtmlString(sb.ToString());
 138:          }
 139:          #endregion
 140:      }
 141:  }
 142:   

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 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:  <h2>Index</h2>
   9:   
  10:  @Html.CheckBoxList("city", (List<CheckBoxListInfo>)ViewData["CheckBoxListOfCities"],null,3)

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

结果:

MVC扩展生成CheckBoxList并水平排列

参考资料:

※  CheckBoxList Helper for MVC        
※  Kevin Tseng