【问题标题】:Adding html class tag under <option> in Html.DropDownList在 Html.DropDownList 的 <option> 下添加 html 类标签
【发布时间】:2011-09-24 02:37:31
【问题描述】:

我一直在寻找有关如何在我的 html.dropdownlist 上添加 HTML 类标签的答案。这是代码

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

我想为 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");

【问题讨论】:

标签: html asp.net-mvc html-select


【解决方案1】:

我已经为 DropDownlistFor 扩展方法做了这个,而不是你使用的 DropDownList,但你自己可能会弄清楚。这些东西主要是从 MVC 源中复制/粘贴。您可以找到来源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);
    }
}

【讨论】:

  • 这真的很好,除了它缺少(现在?)内部的 GetModelStateValue() 方法。这个问题涵盖了这一点:stackoverflow.com/questions/6967148/…
  • 这里是更正的行:object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
  • 我最终采用了相同的方法,以便获得 html 选择集的“标题”属性。这允许您显示更多关于悬停的信息(当然,在移动设备中可能没那么有用)。
  • 对于 GetModelStateValue() 有问题的人,在 Github 上共享的这段代码中使用 GetModelStateValue() 的方法定义(只需复制粘贴到 HtmlHelperExtensions)即可解决问题:Eleven41.Web.Mvc.Bootstrap Github
  • 谁能展示使用扩展所需的 Razor 代码示例?
【解决方案2】:

这是@john-landheer 解决方案的一个小改进版本。

情况有所改善:

  • GetModelStateValue() 的问题已修复
  • 增加DropDownList()扩展方法
  • 不显眼的验证属性将按应有的方式呈现

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    
    namespace App.Infrastructure.Helpers
    {
        public class ExtendedSelectListItem : SelectListItem
        {
            public object HtmlAttributes { get; set; }
        }
    
        public static class ExtendedSelectExtensions
        {
            internal static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType)
            {
                System.Web.Mvc.ModelState modelState;
                if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState))
                {
                    if (modelState.Value != null)
                    {
                        return modelState.Value.ConvertTo(destinationType, null /* culture */);
                    }
                }
                return null;
            }
    
            public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList)
            {
                return ExtendedDropDownList(htmlHelper, name, selectList, (string)null, (IDictionary<string, object>)null);
            }
    
            public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
            {
                return ExtendedDropDownListHelper(htmlHelper, null, name, selectList, optionLabel, htmlAttributes);
            }
    
            public static MvcHtmlString ExtendedDropDownListHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, string expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
            {
                return SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, false, htmlAttributes);
            }
    
            public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
                Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList,
                string optionLabel, object htmlAttributes)
            {
                if (expression == null)
                    throw new ArgumentNullException("expression");
                ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
                return SelectInternal(htmlHelper, metadata, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList,
                    false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            }
    
            private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, 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)
                    ? htmlHelper.GetModelStateValue(fullName, typeof(string[]))
                    : 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 (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.
                System.Web.Mvc.ModelState modelState;
                if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
                {
                    if (modelState.Errors.Count > 0)
                    {
                        tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                    }
                }
    
                tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(fullName, metadata));
    
                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);
            }
    
        }
    }
    

【讨论】:

  • 太棒了!我试着翻译成 vb.net 有一个警告:Variable 'modelState' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. 这有什么效果吗?
  • 如果有人在循环中使用此帮助程序,并且您使用的是旧版本的 MVC 框架(例如 3、4),请注意有一个 MVC 错误会阻止现有的(预选,例如在编辑页面加载场景中)要正确标记的值(即,该值的 option 元素缺少 selected="selected" 属性)。看我的回答here
  • 从 2020 年开始,如果将其与收藏品一起使用,您将需要在 htmlHelper.GetModelStateValue 中使用 name 而不是 fullname,这样您就不会在姓名。此外,为了使默认(预选)值起作用,您还需要像这样在 htmlHelper.GetModelStateValue 函数中使用反射,因为这些值尚未在 ModelState 中:else if (htmlHelper.ViewData.Model != null) { return htmlHelper.ViewData.Model.GetType().GetProperty(key).GetValue(htmlHelper.ViewData.Model, null);}
【解决方案3】:

这对于 ASP.NET MVC 中内置的 DropDownList 帮助程序是不可能的。因此,如果您需要这样做,您将不得不编写自己的助手。您可以查看使用 TagBuilder 生成选项的 ASP.NET MVC 的源代码,您可以在自定义实现中附加任何属性。另一个不太优雅的解决方案是在视图中手动循环遍历数据集并生成单独的选项元素。

【讨论】:

  • 知道这是否已包含在较新版本的框架(5.2.3)中吗?您必须编写自定义代码才能实现非常常见的使用行为,这很蹩脚:(
【解决方案4】:

我首先想到的是这里的 JQuery。您可以使用以下代码轻松完成此操作:

$("#bla").find("option").addClass("poo");

【讨论】:

  • 我不能那样做。我需要该类来更改我的链式选择的值。
  • @paul 好的,但这并不意味着它不起作用。将上面的代码放在你需要的 JQuery 代码之前,然后在你需要它们之前设置类。
  • 我只想补充一点,我认为这是一种快速而简洁的方法。默认的 html 助手在 MVC 中很好,通过 jquery 添加类很快。是的,这可能会出现在非 js 浏览器中,但是......现在谁禁用了 js? 1.5% 的人口是谁。
  • @gerdi 如果你有禁用 JS 的浏览器,你不值得浏览 :)
  • 这比编写扩展方法简单得多。这不是首先使用视图引擎的重点吗?这不仅有效,而且我相信它确实解决了@paul 的担忧。只要它在 $(document).ready(function() {}) 中,该类选择器将在文档完成加载/渲染这些 dom 对象后的任何时候可用。
【解决方案5】:

一个简单的解决方案: 当你添加

@Html.DropDownList("someID", new SelectList(Model.selectItems),"--Select--",new { @class= "select-ddl" })

在你的css中再添加一个类

.select-ddl option {}

这个类将应用于 HTML 中的所有选项标签。

【讨论】:

    【解决方案6】:

    我写了一个简单修改html的包装器:

        public static MvcHtmlString DisableFirstItem(MvcHtmlString htmlString)
        {
            return new MvcHtmlString(
                htmlString.ToString()
                .Replace("<option value=\"Unknown\">", 
                         "<option disabled value=\"Unknown\">")
            );
        }
    

    然后我用这个辅助函数包装了我的 DropDownListFor:

            @Html.Raw(MyHtmlHelpers.DisableFirstItem(
    
              Html.DropDownListFor(m => m.Instrument,
                new SelectList(ReflectionHelpers.GenerateEnumDictionary<OrderInstrument>(true), "Key", "Value", Model.Instrument),
                new { @class = "form-control" })
    
            ))
    

    如果您愿意,显然可以使辅助函数更复杂。

    【讨论】:

      【解决方案7】:

      我修改了@Alexander Puchkov 的答案,以便自动创建一个 ExtendedSelectList,其中包含一组 ExtendedSelectListItems,该集合是从传递给它的 Items 的属性自动生成的,而无需手动指定每个 SelectListItem 的属性。它将属性创建为“data-*”。您可以使用函数 parms 或将它们列在 excludeProperties 中来排除某些属性。

      using System;
      using System.Collections;
      using System.Collections.Generic;
      using System.Globalization;
      using System.Linq;
      using System.Linq.Expressions;
      using System.Reflection;
      using System.Text;
      using System.Web;
      using System.Web.Mvc;
      using System.Web.UI;
      
      namespace App.Infrastructure.Helpers.Extensions
      {
          public class ExtendedSelectList : SelectList
          {
              static readonly string[] excludedProperties = new string[] { "DateInsert", "DateUpdate" }; // Write here properties you want to exclude for every ExtendedSelectList
              public ICollection<ExtendedSelectListItem> ExtendedSelectListItems { get; set; }
              public ExtendedSelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue, params string[] exclude) : base(items, dataValueField, dataTextField, selectedValue)
              {
                  ExtendedSelectListItems = new List<ExtendedSelectListItem>();
                  exclude = exclude.Concat(new string[] { dataValueField, dataTextField }).ToArray();
                  exclude = exclude.Concat(excludedProperties).ToArray();
                  foreach (var selectListItem in this.AsEnumerable())
                  {
                      var extendedItem = new ExtendedSelectListItem() { Value = selectListItem.Value, Text = selectListItem.Text, Selected = selectListItem.Selected, Disabled = selectListItem.Disabled, Group = selectListItem.Group };
                      var htmlAttributes = new Dictionary<string, object>();
                      var item = items.Cast<object>().FirstOrDefault(x =>
                      {
                          string valueItem = DataBinder.Eval(x, DataValueField).ToString();
                          string valueSelectListItem = DataBinder.Eval(selectListItem, "Value").ToString();
                          return valueItem == valueSelectListItem;
                      });
                      foreach (PropertyInfo property in item.GetType().GetProperties())
                      {
                          if (!property.CanRead || (property.GetIndexParameters().Length > 0) || (exclude != null && exclude.Contains(property.Name)))
                              continue;
      
                          htmlAttributes.Add("data-" + property.Name.ToLower(), property.GetValue(item));
                      }
                      extendedItem.HtmlAttributesDict = htmlAttributes;
                      ExtendedSelectListItems.Add(extendedItem);
                  }
              }
          }
          public class ExtendedSelectListItem : SelectListItem
          {
              public object HtmlAttributes { get; set; }
              public Dictionary<string, object> HtmlAttributesDict { get; set; }
          }
      
          public static class ExtendedSelectExtensions
          {
              internal static object GetModelStateValue(this HtmlHelper htmlHelper, string key, Type destinationType)
              {
                  System.Web.Mvc.ModelState modelState;
                  if (htmlHelper.ViewData.ModelState.TryGetValue(key, out modelState))
                  {
                      if (modelState.Value != null)
                      {
                          return modelState.Value.ConvertTo(destinationType, null /* culture */);
                      }
                  }
                  return null;
              }
      
              public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList)
              {
                  return ExtendedDropDownList(htmlHelper, name, selectList, (string)null, (IDictionary<string, object>)null);
              }
      
              public static MvcHtmlString ExtendedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
              {
                  return ExtendedDropDownListHelper(htmlHelper, null, name, selectList, optionLabel, htmlAttributes);
              }
      
              public static MvcHtmlString ExtendedDropDownListHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, string expression, IEnumerable<ExtendedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
              {
                  return SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, false, htmlAttributes);
              }
      
              public static MvcHtmlString ExtendedDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
                  Expression<Func<TModel, TProperty>> expression, IEnumerable<ExtendedSelectListItem> selectList,
                  string optionLabel, object htmlAttributes)
              {
                  if (expression == null)
                      throw new ArgumentNullException("expression");
                  ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
                  return SelectInternal(htmlHelper, metadata, optionLabel, ExpressionHelper.GetExpressionText(expression), selectList,
                      false /* allowMultiple */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
              }
      
              private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, 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)
                      ? htmlHelper.GetModelStateValue(fullName, typeof(string[]))
                      : 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 (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.
                  System.Web.Mvc.ModelState modelState;
                  if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
                  {
                      if (modelState.Errors.Count > 0)
                      {
                          tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                      }
                  }
      
                  tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(fullName, metadata));
      
                  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";
                  }
                  var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(item.HtmlAttributes);
                  builder.MergeAttributes(attributes);
                  if (item.HtmlAttributesDict != null)
                  {
                      foreach (var attribute in item.HtmlAttributesDict)
                      {
                          var key = attribute.Key.ToLower(); // We call ToLower to keep the same naming convention used by MVC's HtmlHelper.AnonymousObjectToHtmlAttributes
                          var value = attribute.Value?.ToString() ?? "";
                          builder.Attributes[key] = value;
                      }
                  }
                  return builder.ToString(TagRenderMode.Normal);
              }
      
          }
      }
      

      要在 Razor 中使用它:

      @{
          var availableLocations = new ExtendedSelectList(Model.AvailableLocations, "Id", "Value", Model.LocationId);
      }
      @Html.ExtendedDropDownListFor(m => Model.LocationId, availableLocations.ExtendedSelectListItems, null, new { id = "ddLocation" })
      

      请注意“availableLocations.ExtendedSelectListItems”,因为您不能直接使用 Enumerable 项目,因为它们是简单的 SelectListItem

      【讨论】:

        猜你喜欢
        • 2012-03-25
        • 2017-09-17
        • 2018-04-16
        • 1970-01-01
        • 2014-10-01
        • 2011-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多