根据&LT添加HTML标签类;选项>在Html.DropDownList [英] Adding html class tag under <option> in Html.DropDownList

查看:410
本文介绍了根据&LT添加HTML标签类;选项>在Html.DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找如何在我的html.dropdownlist添加HTML标签类的答案。这里是code

 <%:Html.DropDownList(包标识,新的SelectList(计算机[包]为IEnumerable,包标识,姓名,Model.PackageId))% >

我要添加类的选项中选择元素,这样我可以使用这个链接中选择:

 <选择一个id =类别>
  <期权价值=1>的One< /选项>
  <期权价值=2>二< /选项>
< /选择>
<选择ID =一揽子>
  <期权价值=1级=1 - 酮 - 包装1< /选项>
  <期权价值=2级=1 - 酮 - 包装2< /选项>
  <期权价值=3级=2>二 - 包装1< /选项>
  <期权价值=4级=2>二 - 包装2< /选项>
< /选择>$(#系列)链接(#标)。


解决方案

我做这个的DropDownlistFor扩展方法,不使用DropDownList的,但你也许可以明白这一点你自己。这东西大多是从MVC源复制/粘贴。你可以找到源头这里

 公共类ExtendedSelectListItem:SelectListItem
{
    公共对象htmlAttributes {搞定;组; }
}公共静态部分类HtmlHelperExtensions
{
    公共静态MvcHtmlString ExtendedDropDownListFor<的TModel,TProperty>(此的HtmlHelper<的TModel>的HtmlHelper,防爆pression< Func键<的TModel,TProperty>>前pression,IEnumerable的< ExtendedSelectListItem>选择列表,串optionLabel,对象htmlAttributes)
    {
        返回SelectInternal(的HtmlHelper,optionLabel,防爆pressionHelper.GetEx pressionText(如pression),选择列表,虚假/ * *的AllowMultiple /,HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }    私有静态MvcHtmlString SelectInternal(此的HtmlHelper的HtmlHelper,串optionLabel,字符串名称,IEnumerable的< ExtendedSelectListItem>选择列表,布尔的AllowMultiple,IDictionary的<字符串对象> htmlAttributes)
    {
        字符串全名= htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(名);
        如果(String.IsNullOrEmpty(全名))
            抛出新的ArgumentException(NO NAME);        如果(选择列表== NULL)
            抛出新的ArgumentException(不选择列表);        对象设置defaultValue =(的AllowMultiple)? GetModelStateValue(的HtmlHelper,全名的typeof(字符串[])):GetModelStateValue(的HtmlHelper,全名的typeof(字符串));        //如果我们还未使用的ViewData获取项目的完整列表,然后我们需要
        //使用参数提供的值之前使用的ViewData提供的值。
        如果(设置defaultValue == NULL)
            设置defaultValue = htmlHelper.ViewData.Eval(全名);        如果(设置defaultValue!= NULL)
        {
            IEnumerable的defaultValues​​ =(的AllowMultiple)?设置defaultValue为IEnumerable:新的[] {}设置defaultValue;
            IEnumerable的<串GT;从defaultValues​​对象值选择Convert.ToString(值,CultureInfo.CurrentCulture)值=;
            HashSet的<串GT; selectedValues​​ =新的HashSet<串GT;(价值观,StringComparer.OrdinalIgnoreCase);
            清单< ExtendedSelectListItem> newSelectList =新的List< ExtendedSelectListItem>();            的foreach(在选择列表ExtendedSelectListItem项)
            {
                item.Selected =(item.Value!= NULL)? selectedValues​​.Contains(item.Value):selectedValues​​.Contains(item.Text);
                newSelectList.Add(项目);
            }
            选择列表= newSelectList;
        }        //每个列表项转换为一个<选项>标签
        StringBuilder的listItemBuilder =新的StringBuilder();        //使optionLabel是被呈现的第一个项目。
        如果(optionLabel!= NULL)
            listItemBuilder.Append(ListItemToOption(新ExtendedSelectListItem(){文字= optionLabel,值=的String.Empty,选择= FALSE}));        的foreach(在选择列表ExtendedSelectListItem项)
        {
            listItemBuilder.Append(ListItemToOption(项目));
        }        TagBuilder tagBuilder =新TagBuilder(选择)
        {
            的innerHTML = listItemBuilder.ToString()
        };
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute(姓名,全名,真/ * replaceExisting * /);
        tagBuilder.GenerateId(全名);
        如果(的AllowMultiple)
            tagBuilder.MergeAttribute(多,多);        //如果有一个名为字段的任何错误,我们添加的CSS属性。
        ModelState中的ModelState;
        如果(htmlHelper.ViewData.ModelState.TryGetValue(全名,出的ModelState))
        {
            如果(modelState.Errors.Count大于0)
            {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }        tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(名));        返回MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
    }    内部静态字符串ListItemToOption(ExtendedSelectListItem项)
    {
        TagBuilder建设者=新TagBuilder(选项)
        {
            的innerHTML = HttpUtility.HtmlEn code(item.Text)
        };
        如果(item.Value!= NULL)
        {
            builder.Attributes [值] = item.Value;
        }
        如果(item.Selected)
        {
            builder.Attributes [选择] =选择;
        }
        builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(item.htmlAttributes));
        返回builder.ToString(TagRenderMode.Normal);
    }
}

I've been looking for answers on how to add an HTML class tag on my html.dropdownlist. here is the code

<%: Html.DropDownList("PackageId", new SelectList(ViewData["Packages"] as IEnumerable, "PackageId", "Name", Model.PackageId))%>

I want to add classes for options under the select element so that I can use this chained select :

<select id="category">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>
<select id="package">
  <option value="1" class="1">One - package1</option>
  <option value="2" class="1">One - package2</option>
  <option value="3" class="2">Two - package1</option>
  <option value="4" class="2">Two - package2</option>
</select>

$("#series").chained("#mark");

解决方案

I've done this for the DropDownlistFor extension method, not the DropDownList you use, but you can probably figure that out yourself. This stuff is mostly copy/paste from the MVC sources. You can find the sources here.

public class ExtendedSelectListItem : SelectListItem
{
    public object htmlAttributes { get; set; }
}

public static partial class HtmlHelperExtensions
{
    public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, object htmlAttributes)
    {
        return SelectInternal(htmlHelper, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList, false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<ExtendedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
    {
        string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
        if (String.IsNullOrEmpty(fullName))
            throw new ArgumentException("No name");

        if (selectList == null)
            throw new ArgumentException("No selectlist");

        object defaultValue = (allowMultiple) ? GetModelStateValue(htmlHelper, fullName, typeof(string[])) : GetModelStateValue(htmlHelper, 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 (defaultValue == null)
            defaultValue = htmlHelper.ViewData.Eval(fullName);

        if (defaultValue != null)
        {
            IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : 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<ExtendedSelectListItem> newSelectList = new List<ExtendedSelectListItem>();

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

        // Convert each ListItem to an <option> tag
        StringBuilder listItemBuilder = new StringBuilder();

        // Make optionLabel the first item that gets rendered.
        if (optionLabel != null)
            listItemBuilder.Append(ListItemToOption(new ExtendedSelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));

        foreach (ExtendedSelectListItem item in selectList)
        {
            listItemBuilder.Append(ListItemToOption(item));
        }

        TagBuilder tagBuilder = new TagBuilder("select")
        {
            InnerHtml = listItemBuilder.ToString()
        };
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("name", fullName, true /* replaceExisting */);
        tagBuilder.GenerateId(fullName);
        if (allowMultiple)
            tagBuilder.MergeAttribute("multiple", "multiple");

        // If there are any errors for a named field, we add the css attribute.
        ModelState modelState;
        if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
        {
            if (modelState.Errors.Count > 0)
            {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }

        tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name));

        return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
    }

    internal static string ListItemToOption(ExtendedSelectListItem item)
    {
        TagBuilder builder = new TagBuilder("option")
        {
            InnerHtml = HttpUtility.HtmlEncode(item.Text)
        };
        if (item.Value != null)
        {
            builder.Attributes["value"] = item.Value;
        }
        if (item.Selected)
        {
            builder.Attributes["selected"] = "selected";
        }
        builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(item.htmlAttributes));
        return builder.ToString(TagRenderMode.Normal);
    }
}

这篇关于根据&LT添加HTML标签类;选项&GT;在Html.DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆