MVC通过扩展HtmlHelper实现RadioButtonList



RadioButtonList在Web页面应用非常广泛,在传统的ASP.NET aspx中系统自带有RadioButtonList控件,但是在MVC Razer中没有提供,下面介绍通过扩展HtmlHelper实现RadioButtonList的方法

 
 
 
public static class RRadioButtonListelper
    {
        public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name)
        {
            return RadioButtonList(helper, name, helper.ViewData[name] as IEnumerable<SelectListItem>, new { });
        }
        
        public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList)
        {
            return RadioButtonList(helper, name, selectList, new { });
        }

        public static MvcHtmlString RadioButtonList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)
        {
            IDictionary<string, object> HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            HtmlAttributes.Add("type", "radio");
            HtmlAttributes.Add("name", name);

            StringBuilder stringBuilder = new StringBuilder();
            int i = 0;
            int j = 0;
            foreach (SelectListItem selectItem in selectList)
            {
                string id = string.Format("{0}{1}", name, j++);
                
                IDictionary<string, object> newHtmlAttributes = HtmlAttributes.IDictionaryCopy();
                newHtmlAttributes.Add("value", selectItem.Value);
                newHtmlAttributes.Add("id", id);
                var selectedValue = (selectList as SelectList).SelectedValue;
                if (selectedValue == null)
                {
                    if (i++ == 0)
                        newHtmlAttributes.Add("checked", null);
                }
                else if (selectItem.Value == selectedValue.ToString())
                {
                    newHtmlAttributes.Add("checked", null);
                }

                TagBuilder tagBuilder = new TagBuilder("input");
                tagBuilder.MergeAttributes<string, object>(newHtmlAttributes);
                string inputAllHtml = tagBuilder.ToString(TagRenderMode.SelfClosing);
                stringBuilder.AppendFormat(@" {0}  <label for='{2}'>{1}</label>",
                   inputAllHtml, selectItem.Text, id);
            }
            return MvcHtmlString.Create(stringBuilder.ToString());

        }
        private static IDictionary<string, object> IDictionaryCopy(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;
        }

        public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
        {
            return RadioButtonListFor<TModel, TProperty>(htmlHelper, expression, selectList, null);
        }

        public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
        {
            ModelState state;
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }
            if (selectList == null)
            {
                throw new ArgumentNullException("selectList");
            }
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
            string name = ExpressionHelper.GetExpressionText(expression);
            string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            if (string.IsNullOrEmpty(fullHtmlFieldName))
            {
                throw new ArgumentException("name", "name");
            }

            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach(SelectListItem item in selectList)
            {
                TagBuilder tabBuilder = new TagBuilder("input");
                tabBuilder.MergeAttribute("name", fullHtmlFieldName, true);
                string id =string.Format("{0}_{1}", fullHtmlFieldName, i++);
                tabBuilder.MergeAttribute("id", id, true);
                tabBuilder.Attributes["type"] = "radio";
                if (item.Value != null)
                {
                    tabBuilder.Attributes["value"] = item.Value;
                }
                object selectedValue = null;
                if (selectList is SelectList)
                {
                    selectedValue = (selectList as SelectList).SelectedValue;
                }
                if (selectedValue != null && item.Value==selectedValue.ToString())
                {
                    tabBuilder.Attributes["checked"] = "checked";
                }
                builder.AppendLine(string.Format(" {0}  <label for='{2}'>{1}</label>",
                tabBuilder.ToString(TagRenderMode.Normal), item.Text, id));
            }
            TagBuilder tagBuilder = new TagBuilder("span")
            {
                InnerHtml = builder.ToString()
            };
            tagBuilder.MergeAttributes<string, object>(htmlAttributes);
            if (htmlHelper.ViewData.ModelState.TryGetValue(fullHtmlFieldName, out state) && (state.Errors.Count > 0))
            {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
            tagBuilder.MergeAttributes<string, object>(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));
            return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
        }
    }


参考资料:MVC通过扩展HtmlHelper实现RadioButtonList   http://www.studyofnet.com/news/1196.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值