您的位置:首页 > 其它

MVC扩展生成CheckBoxList并水平排列

2014-03-17 01:05 363 查看
本篇体验生成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>();


[code]ViewBag.Roles = roles;

[/code]

.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


[code] select r.ID).ToList<int>();


ViewBag.OleRoleIDs = existingRoleIds;

[/code]

.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、前台视图遍历所有角色

List<int> roleIds = (List<int>)ViewBag.OleRoleIDs;


[code]for(int i = 0; i < ((List<Role>)ViewBag.Roles).Count(); i++)


{


var item = ((List<Role>)ViewBag.Roles)[i];


string name = "ckb_" + item.ID; //checkbox的name属性


if(i != 0 && i % 3 ==0) //每行有3个checkbox


{


<br />


}


if(roleIds.Contain(item.ID))


{


<span>


<input type="checkbox" checked="checked" id="@item.ID" name="@name" />


<label for="@item.ID">@item.RoleName</label>


</span>


}


else


{


<span>


<input type="checkbox" id="@item.ID" name="@name" />


<label for="@item.ID">@item.RoleName</label>


</span>


}


}

[/code]

.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集合,保存到数据库。

[HttpPost]


[code]public ActionResult SomeActionMethod(FormCollection collection)


{


List<int> roleIds = new List<int>();


var temp = from key in collection.AllKeys


where key.Contains("ckb_")


select key;


 


foreach(var item in temp)


 {


if(Request.Form[item] == "on") //如果checkbox状态为被选中


 {


roleIds.Add(int.Parse(item.Replace("ckb_","")));


 }


 }


 


//TODO:调用服务层方法,删除原来所有的角色,添加新的角色


rreturn Content("ok");


}

[/code]

.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

namespace MvcCblist.Models


[code]{


public class City


{


public int Sort { get; set; }


public string Name { get; set; }


}


}

[/code]

.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渲染出来。

namespace MvcCblist.Models


[code]{


public class CheckBoxListInfo


{


public string Value { get; private set; }


public string DisplayText { get; private set; }


public bool IsChecked { get; private set; }


 


public CheckBoxListInfo(string value, string displayText, bool isChecked)


{


this.Value = value;


this.DisplayText = displayText;


this.IsChecked = IsChecked;


}


}


}

[/code]

.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

using System;


[code]using System.Collections.Generic;


using System.Linq;


using System.Web;


using System.Web.Mvc;


using MvcCblist.Models;


 


namespace MvcCblist.Controllers


{


public class HomeController : Controller


{


public ActionResult Index()


{


List<City> cities = new List<City>()


{


new City(){Sort = 1,Name = "济南市"},


new City(){Sort = 2,Name = "青岛市"},


new City(){Sort = 3,Name = "平度市"},


new City(){Sort = 4, Name = "即墨市"},


new City(){Sort = 5,Name = "威海市"},


new City(){Sort = 6,Name = "淄博市"},


new City(){Sort = 7, Name = "泰安市"}


};


 


List<CheckBoxListInfo> infos = new List<CheckBoxListInfo>();


foreach (City item in cities)


{


infos.Add(new CheckBoxListInfo(item.Sort.ToString(),string.Concat(item.Name,"-",item.Sort.ToString()),false));


}


ViewData["CheckBoxListOfCities"] = infos;


return View();


}


 


}


}


 

[/code]

.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,就像其它内置帮助方法一样

 

using System.Collections.Generic;


[code]using System.Text;


using System.Web.Routing;


using MvcCblist.Models;


 


namespace System.Web.Mvc


{


public static class InputExtensions


{


//name对应input的属性name


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,


List<CheckBoxListInfo> listInfos, IDictionary<string, object> htmlAttributes)


{


if (string.IsNullOrEmpty(name))


{


throw new ArgumentException("此参数不能为空","name");


}


if (listInfos == null)


{


throw new ArgumentException("listInfos");


}


StringBuilder sb = new StringBuilder();


foreach (CheckBoxListInfo info in listInfos)


{


TagBuilder builder = new TagBuilder("input");


if (info.IsChecked)


{


builder.MergeAttribute("checked","checked");


}


builder.MergeAttributes(htmlAttributes);


builder.MergeAttribute("type", "checkbox");


builder.MergeAttribute("name",name);


builder.InnerHtml = info.DisplayText;


sb.Append(builder.ToString(TagRenderMode.Normal));


sb.Append("<br />");


}


return new MvcHtmlString(sb.ToString());


}


 


//重载方法:不含属性键值对集合


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,


List<CheckBoxListInfo> listInfos)


{


return htmlHelper.CheckBoxList(name, listInfos, null);


}


 


//重载方法:从路由中拿数据


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name,


List<CheckBoxListInfo> listInfos, object htmlAttributes)


{


return htmlHelper.CheckBoxList(name, listInfos,


((IDictionary<string, object>) new RouteValueDictionary(htmlAttributes)));


}


}


}


 

[/code]

.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视图

@using System.Web.UI.WebControls


[code]@using MvcCblist.Models


@{


ViewBag.Title = "Index";


Layout = "~/Views/Shared/_Layout.cshtml";


}


 


<h2>Index</h2>


 


@Html.CheckBoxList("city", (List<CheckBoxListInfo>)ViewData["CheckBoxListOfCities"],null)


 

[/code]

.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; }

 

效果:





 

这还不够,我们希望每行多显示几个checkbox。

 

  完善扩展方法,使checkbox能水平排开,并可设置每行的个数

□ 考虑水平排开和每行显示个数的扩展方法

using System.Collections.Generic;


[code]using System.Text;


using System.Web.Routing;


using MvcCblist.Models;


 


namespace System.Web.Mvc


{


public static class InputExtensions


{


#region CheckBoxList


/// <summary>


/// CheckBoxList.


/// </summary>


/// <param name="htmlHelper">The HTML helper.</param>


/// <param name="name">The name.</param>


/// <param name="listInfo">CheckBoxListInfo.</param>


/// <returns></returns>


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo)


{


return htmlHelper.CheckBoxList


(


name,


listInfo,


    (IDictionary<string, object>)null,


0


);


}


/// <summary>


/// CheckBoxList.


/// </summary>


/// <param name="htmlHelper">The HTML helper.</param>


/// <param name="name">The name.</param>


/// <param name="listInfo">CheckBoxListInfo.</param>


/// <param name="htmlAttributes">The HTML attributes.</param>


/// <returns></returns>


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, object htmlAttributes)


{


return htmlHelper.CheckBoxList


(


name,


listInfo,


    (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes),


0


);


}


/// <summary>


/// CheckBoxList.


/// </summary>


/// <param name="htmlHelper">The HTML helper.</param>


/// <param name="name">The name.</param>


/// <param name="listInfo">The list info.</param>


/// <param name="htmlAttributes">The HTML attributes.</param>


/// <returns></returns>


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, IDictionary<string, object> htmlAttributes)


{


if (String.IsNullOrEmpty(name))


{


throw new ArgumentException("必须给CheckBoxList一个Tag Name", "name");


}


if (listInfo == null)


{


throw new ArgumentNullException("必须要设置List<CheckBoxListInfo> listInfo");


}


if (listInfo.Count < 1)


{


throw new ArgumentException("List<CheckBoxListInfo> listInfo 至少要一组资料", "listInfo");


}


StringBuilder sb = new StringBuilder();


int lineNumber = 0;


foreach (CheckBoxListInfo info in listInfo)


{


lineNumber++;


TagBuilder builder = new TagBuilder("input");


if (info.IsChecked)


{


builder.MergeAttribute("checked", "checked");


}


builder.MergeAttributes<string, object>(htmlAttributes);


builder.MergeAttribute("type", "checkbox");


builder.MergeAttribute("value", info.Value);


builder.MergeAttribute("name", name);


builder.InnerHtml = string.Format(" {0} ", info.DisplayText);


sb.Append(builder.ToString(TagRenderMode.Normal));


sb.Append("</br>");


}


return new MvcHtmlString(sb.ToString());


}


/// <summary>


/// CheckBoxList.


/// </summary>


/// <param name="htmlHelper">The HTML helper.</param>


/// <param name="name">The name.</param>


/// <param name="listInfo">The list info.</param>


/// <param name="htmlAttributes">The HTML attributes.</param>


/// <param name="direction">The direction.</param>


/// <param name="number">每行的显示个数.</param>


/// <returns></returns>


public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, List<CheckBoxListInfo> listInfo, IDictionary<string, object> htmlAttributes, int number)


{


if (String.IsNullOrEmpty(name))


{


throw new ArgumentException("必须给这些CheckBoxList一个Tag Name", "name");


}


if (listInfo == null)


{


throw new ArgumentNullException("必须要设置List<CheckBoxListInfo> listInfo");


}


if (listInfo.Count < 1)


{


throw new ArgumentException("List<CheckBoxListInfo> listInfo 至少要有一组资料", "listInfo");


}


StringBuilder sb = new StringBuilder();


int lineNumber = 0;


foreach (CheckBoxListInfo info in listInfo)


{


lineNumber++;


TagBuilder builder = new TagBuilder("input");


if (info.IsChecked)


{


builder.MergeAttribute("checked", "checked");


}


builder.MergeAttributes<string, object>(htmlAttributes);


builder.MergeAttribute("type", "checkbox");


builder.MergeAttribute("value", info.Value);


builder.MergeAttribute("name", name);


builder.InnerHtml = string.Format(" {0} ", info.DisplayText);


sb.Append(builder.ToString(TagRenderMode.Normal));


if (number == 0)


{


    sb.Append("<br />");


}


            else if (lineNumber % number == 0)


{


    sb.Append("<br />");


}


}


return new MvcHtmlString(sb.ToString());


}


#endregion


}


}


 

[/code]

.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视图

@using System.Web.UI.WebControls


[code]@using MvcCblist.Models


@{


ViewBag.Title = "Index";


Layout = "~/Views/Shared/_Layout.cshtml";


}


 


<h2>Index</h2>


 


@Html.CheckBoxList("city", (List<CheckBoxListInfo>)ViewData["CheckBoxListOfCities"],null,3)

[/code]

.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; }

 

结果:





参考资料:

※  CheckBoxList Helper for MVC        
※  Kevin Tseng
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: