zoukankan      html  css  js  c++  java
  • asp.net Mvc3 扩展 RadioButtonFor 为 RadioButtonListFor


       Mvc 3 中 有RadioButtonFor 但是没有list,扩展一下,方法如下:

       

       

    View Code
    public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<stringobject> htmlAttributes)
            {
                if (expression == null)
                {
                    throw new ArgumentNullException("expression");
                }
                string name = ExpressionHelper.GetExpressionText(expression);

                string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
                if (String.IsNullOrEmpty(fullName))
                {
                    throw new ArgumentException("name");
                }

                bool usedViewData = false;

                // If we got a null selectList, try to use ViewData to get the list of items.
                if (selectList == null)
                {
                    selectList = htmlHelper.GetSelectData(fullName);
                    usedViewData = true;
                }

                object defaultValue = htmlHelper.GetModelStateValue(fullName, typeof(string));

                // If we haven't already used ViewData to get the entire list of items then we need to
                
    // use the ViewData-supplied value before using the parameter-supplied value.
                if (!usedViewData)
                {
                    if (defaultValue == null)
                    {
                        defaultValue = htmlHelper.ViewData.Eval(fullName);
                    }
                }
                if (defaultValue != null)
                {
                    IEnumerable defaultValues =  new[] { defaultValue };
                    IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
                    HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
                    List<SelectListItem> newSelectList = new List<SelectListItem>();

                    foreach (SelectListItem item in selectList)
                    {
                        item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);
                        newSelectList.Add(item);
                    }
                    selectList = newSelectList;
                }


                #region  

                TagBuilder table = new TagBuilder("table");
                int i = 0;

                foreach (SelectListItem item in selectList)
                {
                    //
                    TagBuilder tr = new TagBuilder("tr");
                    i++;
                    string id = string.Format("{0}_{1}", name, i);
                    TagBuilder td = new TagBuilder("td");
                    td.InnerHtml = GenerateRadioHtml(name, id, item.Text, item.Value, item.Selected, htmlAttributes);
                    tr.InnerHtml = td.ToString();
                    table.InnerHtml += tr.ToString();
                }

                #endregion

                return new MvcHtmlString(table.ToString());
            }

      还有:

       

    View Code
    private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
            {
                object o = null;
                if (htmlHelper.ViewData != null)
                {
                    o = htmlHelper.ViewData.Eval(name);
                }
                if (o == null)
                {
                    throw new InvalidOperationException(
                            "IEnumerable<SelectListItem>");
                }
                IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
                if (selectList == null)
                {
                    throw new InvalidOperationException(
                            "IEnumerable<SelectListItem>");
                }
                return selectList;
        

       

      

    View Code
     private static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType)
            {
                ModelState modelState;
                if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState))
                {
                    if (modelState.Value != null)
                    {
                        return modelState.Value.ConvertTo(destinationType, null /* culture */);
                    }
                }
                return null;
            }

     

    View Code
    private static string GenerateRadioHtml(string name, string id, string labelText, string value, bool isChecked, IDictionary<stringobject> htmlAttributes)
            {
                StringBuilder sb = new StringBuilder();

                TagBuilder label = new TagBuilder("label");
                label.MergeAttribute("for", id);
                label.SetInnerText(labelText);

                TagBuilder input = new TagBuilder("input");
                input.GenerateId(id);
                input.MergeAttribute("name", name);
                input.MergeAttribute("type""radio");
                input.MergeAttribute("value", value);
                input.MergeAttributes(htmlAttributes);
                if (isChecked)
                {
                    input.MergeAttribute("checked""checked");
                }
                sb.AppendLine(input.ToString());
                sb.AppendLine(label.ToString());
                return sb.ToString();
            }

            页面使用如下:

           
    @Html.RadioButtonListFor(c => c.ModelType, ((IEnumerable<ParmInfo>)ViewBag.Test).Select(m => new 
               SelectListItem { Text = m.parmName, Value = m.parmValue, Selected = (m.parmValue == "0") }), "", null)

         最终形成如下图所示:

         

       

  • 相关阅读:
    [翻译] JSAnimatedImagesView
    css3 :nth-child 常用用法
    设置屏幕亮度(系统级别和应用级别)
    nodejs 改变全局前缀
    MongoDB数据库和集合的状态信息
    NoSQL架构实践(一)——以NoSQL为辅
    socket.io,系统api,
    svn sc create 命令行创建服务自启动
    background-size background-positon合并的写法
    【转】视频编码与封装方式详解
  • 原文地址:https://www.cnblogs.com/lpe110/p/2417396.html
Copyright © 2011-2022 走看看