mvc3 CheckBoxList扩展

2012-08-01

mvc3 CheckBoxList扩展,mvc3的模板也有很多html扩展,但是好像实现了部分重点的,有时候还需要这样去扩展,其实这样是对的,总得给程序员留点空间吧。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;

namespace Syw.Framework.Mvc
{
     public static class CheckBoxListExtensions
    {
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList)
        {
            return CheckBoxList(helper, name, selectList, new { });
        }
        public static MvcHtmlString CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)
        {

            IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            HtmlAttributes.Add("type", "checkbox");
            HtmlAttributes.Add("id", name);
            HtmlAttributes.Add("name", name);
            //HtmlAttributes.Add("style", "margin:0 0 0 10px;line-height:30px; vertical-align:-8px;border:none;");

            StringBuilder stringBuilder = new StringBuilder();

            foreach (SelectListItem selectItem in selectList)
            {
                IDictionary<string, object> newHtmlAttributes = HtmlAttributes.DeepCopy();
                newHtmlAttributes.Add("value", selectItem.Value);
                if (selectItem.Selected)
                {
                    newHtmlAttributes.Add("checked", "checked");
                }

                TagBuilder tagBuilder = new TagBuilder("input");
                tagBuilder.MergeAttributes<string, object>(newHtmlAttributes);
                string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing);
                stringBuilder.AppendFormat(@"<label style=""margin:0 0 0 10px;""> {0}  {1}</label>",
                   inputAllHtml, selectItem.Text);
            }
            return MvcHtmlString.Create(stringBuilder.ToString());

        }
        private static IDictionary<string, object> DeepCopy(this IDictionary<string, object> ht)
        {
            Dictionary<string, object> _ht = new Dictionary<string, object>();

            foreach (var p in ht)
            {
                _ht.Add(p.Key, p.Value);
            }
            return _ht;
        } 

    }
}

调用的时候需要在模板上引用@using Syw.Framework.Mvc;

这样就可以直接@Html.CheckBoxList("ItemType", Model.ItemList)这样调用扩展了

 

作者:robotbird, 分类:关于代码 标签: donet mvc donet , 浏览(5535), 评论(1)
上一篇: VS2008 解决方案配置器,即DEBUG,RELEASE 模式选择(转载)
下一篇: 从今天开始坚持不刷技术类文章

相关文章

(1)条评论 订阅

  1. ${item.nickname} 币安链 说:

    但是好像实现了部分重点的

1

发表评论

电子邮件用于回复通知和avatar全球唯一头像 *

*