支持 dropdownlist .NET MVC 中的 optgroup?

2023-11-23

从这个问题继续以编程方式创建下拉列表我希望我的清单有几个optgroup也列出了。目前这可能吗?

我知道我需要将 selectList 传递到 dropDownList,但不知道如何将文本、值、optgroup 添加到 selectList。

我希望最终结果产生:

<option value="">Please select</option>
  <optgroup label="Option A">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </optgroup>
  <optgroup label="Option B">
    <option value="a">A</option>
    <option value="b">B</option>
    <option value="c">C</option>
  </optgroup>
</option>

我的扩展有点复杂,但它具有与原始 DropDownList 相同的所有重载。

实际上,我专门创建了它,以便能够生成带有组的 DropDownList 并在以下的帮助下转换为两个连接的选择jDoubleSelect

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;using System.Web.Routing;

public class GroupedSelectListItem : SelectListItem
{
    public string GroupKey { get; set; }
    public string GroupName { get; set; }
}

public static class HtmlHelpers
{
    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name)
    {
        return DropDownListHelper(htmlHelper, name, null, null, null);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList)
    {
        return DropDownListHelper(htmlHelper, name, selectList, null, null);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, string optionLabel)
    {
        return DropDownListHelper(htmlHelper, name, null, optionLabel, null);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList, IDictionary<string, object> htmlAttributes)
    {
        return DropDownListHelper(htmlHelper, name, selectList, null, htmlAttributes);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList, object htmlAttributes)
    {
        return DropDownListHelper(htmlHelper, name, selectList, null, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList, string optionLabel)
    {
        return DropDownListHelper(htmlHelper, name, selectList, optionLabel, null);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
    {
        return DropDownListHelper(htmlHelper, name, selectList, optionLabel, htmlAttributes);
    }

    public static MvcHtmlString DropDownGroupList(this HtmlHelper htmlHelper, string name, IEnumerable<GroupedSelectListItem> selectList, string optionLabel, object htmlAttributes)
    {
        return DropDownListHelper(htmlHelper, name, selectList, optionLabel, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList)
    {
        return DropDownGroupListFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList, object htmlAttributes)
    {
        return DropDownGroupListFor(htmlHelper, expression, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList, IDictionary<string, object> htmlAttributes)
    {
        return DropDownGroupListFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList, string optionLabel)
    {
        return DropDownGroupListFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList, string optionLabel, object htmlAttributes)
    {
        return DropDownGroupListFor(htmlHelper, expression, selectList, optionLabel, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString DropDownGroupListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<GroupedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
    {
        if (expression == null)
        {
            throw new ArgumentNullException("expression");
        }

        return DropDownListHelper(htmlHelper, ExpressionHelper.GetExpressionText(expression), selectList, optionLabel, htmlAttributes);
    }

    private static MvcHtmlString DropDownListHelper(HtmlHelper htmlHelper, string expression, IEnumerable<GroupedSelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
    {
        return SelectInternal(htmlHelper, optionLabel, expression, selectList, false /* allowMultiple */, htmlAttributes);
    }


    // Helper methods

    private static IEnumerable<GroupedSelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
    {
        object o = null;
        if (htmlHelper.ViewData != null)
        {
            o = htmlHelper.ViewData.Eval(name);
        }
        if (o == null)
        {
            throw new InvalidOperationException(
                String.Format(
                    CultureInfo.CurrentCulture,
                    "Missing Select Data"));
        }
        var selectList = o as IEnumerable<GroupedSelectListItem>;
        if (selectList == null)
        {
            throw new InvalidOperationException(
                String.Format(
                    CultureInfo.CurrentCulture,
                    "Wrong Select DataType"));
        }
        return selectList;
    }

    internal static string ListItemToOption(GroupedSelectListItem item)
    {
        var 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";
        }
        return builder.ToString(TagRenderMode.Normal);
    }

    private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<GroupedSelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
    {
        name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
        if (String.IsNullOrEmpty(name))
        {
            throw new ArgumentException("Null Or Empty", "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(name);
            usedViewData = true;
        }

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

        if (defaultValue != null)
        {
            var defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };
            var values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);
            var selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
            var newSelectList = new List<GroupedSelectListItem>();

            foreach (var 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
        var listItemBuilder = new StringBuilder();

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

        foreach (var group in selectList.GroupBy(i => i.GroupKey))
        {
            string groupName = selectList.Where(i => i.GroupKey == group.Key).Select(it => it.GroupName).FirstOrDefault();
            listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\">", groupName, group.Key));
            foreach (GroupedSelectListItem item in group)
            {
                listItemBuilder.AppendLine(ListItemToOption(item));
            }
            listItemBuilder.AppendLine("</optgroup>");
        }

        var tagBuilder = new TagBuilder("select")
        {
            InnerHtml = listItemBuilder.ToString()
        };
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("name", name, true /* replaceExisting */);
        tagBuilder.GenerateId(name);
        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(name, out modelState))
        {
            if (modelState.Errors.Count > 0)
            {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }

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

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

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

支持 dropdownlist .NET MVC 中的 optgroup? 的相关文章

  • 我的 MVC 控制器真的应该了解 JSON 吗?

    JsonResult 类是通过 AJAX 将 Json 作为操作返回给客户端的非常有用的方法 public JsonResult JoinMailingList string txtEmail return new JsonResult D
  • ASP.NET MVC5:想要使用模型绑定更新集合中的多个项目

    所以我有一个用户对象的集合 它应该是可批量编辑的 同时编辑许多用户 我使用实体框架将用户输入保存到数据库中 控制器方法从表单获取的集合为 null 为什么 另外 BindAttribute 是否可以像我的代码中那样与集合一起使用 View
  • 向表单提交添加附加参数

    我的 Razor 视图中有一个表单声明
  • 在同一站点上使用基本身份验证和表单身份验证

    谁能告诉我 是否可以在我的网站上同时使用基本身份验证和表单身份验证 而两者不会相互干扰 我有一个新网站 出于批准目的 我只希望某些人看到该网站 该网站有一个使用表单身份验证的会员区域 现在当任何人在通过基本身份验证后进入该网站时 他们都会被
  • 下拉字段 - 第一项应为空

    在查找列中使用共享点构建并将其设置为必填字段 SharePoint 自动选择下拉框中的第一项 对最终用户来说有点误导 有没有办法让这个下拉框的第一行显示空白或空 我对任何解决方案持开放态度 我更喜欢 javascript 类型的解决方案 对
  • 使用 ViewModel 屏蔽可为 null 的域属性

    我正在使用 Entity Framework 4 0 并使用 POCO 对象 当我从数据库填充 POCO 对象时 我将属性值转换为我自己的域对象 我们可以将其称为我的模型 当然 我的模型的字段是否可为空取决于它在数据库中映射到的值是否来自
  • ASP.NET MVC 使用自定义模型绑定程序时从客户端检测到潜在危险的 Request.Form 值

    在这里得到错误 ValueProviderResult value bindingContext ValueProvider GetValue ConfirmationMessage 如何仅允许选择值 IE ValidateInput fa
  • 维护用户 ID 的最佳实践 (MVC)

    我使用 FormsAuthentication 但添加了自定义 MemberShipProvider 来根据自定义用户表进行验证 所有包含 用户数据 的表都有一个 idUser 列 因此我需要维护用户 id 以便向用户显示他的数据 以前我使
  • ASP.NET MVC - 服务层,每个控制器操作中的单个或多个服务?

    我开始在我的 MVC 项目中实现一个服务层 以精简一些臃肿的控制器 它也有存储库 工作单元模式 我的问题是 如果您的页面有一个复杂的视图模型 其中包含大量子对象等 并且在幕后有大量逻辑发生 让您了解原始开发人员编写的控制器有近 4000 行
  • 全局访问 Ninject 内核

    这个问题与 Ninject 没有具体关系 这更多的是一个一般性的编码问题 但我将其发布在这里 以防在 Ninject 中可能有更好的方法来完全处理该问题 而不是我正在尝试做的事情 我想知道是否可以从 Global asax 中的实例全局访问
  • 如何使用带有 Scripts.Render 的 ASP MVC 4 捆绑包的脚本延迟属性

    我浏览了 Google 和 Stackoverflow 但没有找到答案 是否有任何内置方法可以使捆绑包按延迟执行 或者有人知道有人为此编写的扩展帮助器方法吗 尝试将 Web Optimization 升级到版本 1 1 0Codeplex
  • 如何在控制器中模拟 Automapper (IMapper)

    我正在尝试为现有的 MVC Web 应用程序编写单元测试 我在自动映射器中面临一些问题 IMapper 每当使用地图函数时它都会返回null value 我的控制器代码 public class UserAdministrationCont
  • 在 SelectList 集合中设置所选项目

    我有一堂具有以下属性的课程 它构建了一个SelectList现有列表中的对象 然后设置所选项目 public SelectList ProviderTypeList get SelectList list new SelectList my
  • 使用 MVC 5 RouteArea 属性时找不到默认区域视图

    我有一个包含多个区域的 MVC5 项目 我有一个默认区域 名为Default 并在其中有一个默认控制器 名为DefaultController 这可以通过站点路径访问 RouteArea public class DefaultContro
  • 后退按钮不会导致回发到 MVC 中的控制器操作

    当我在 Win7 上的 IE10 或 Chrome 中单击后退按钮时 它不会到达 MVC 控制器中的断点 IE 开发者工具中的 网络 选项卡显示 304 未修改 并且 Fiddler 未捕获该请求 我期待着回帖 这样我就可以在我的控制器中工
  • 类型违反了继承安全规则:“System.Net.Http.WebRequestHandler”

    我在 MVC 应用程序的 web config 中有以下程序集引用
  • global.asax Application_AcquireRequestState 与 Application_BeginRequest

    有什么不同 我想在我的应用程序中实现语言下拉选择 因此 当选择选定的语言时 将设置线程区域性并重新加载页面 Like so Thread CurrentThread CurrentCulture CultureInfo CreateSpec
  • ASP.NET MVC - 重写 FormMethod.Get 查询字符串?

    我有一个简单的表单 只有一个文本框和一个提交按钮 该表单基本上将文本框中的值作为查询字符串发送到不同的页面 当我单击提交按钮时 查询字符串采用以下格式 例如 mysite com TargetCode Test1 我希望它以这种格式显示 m
  • Bootstrap下拉菜单文本颜色

    所以我第一次使用 Twitter 的 Bootstrap 我试图在下拉菜单折叠后更改其文本的颜色 如果有道理的话 I used 当您压缩网页以显示折叠菜单并转到下拉列表时 您会看到蓝色背景转移到下拉菜单项 但字体颜色为黑色 使其很难阅读 我
  • 找不到 securityToken 的有效键映射

    我正在开发测试应用程序 用于在 MVC ASP net Visual studio 2013 中显示经过身份验证的身份声明 我已通过以下方式从活动目录进行身份验证 1 在解决方案中添加新的mvc项目 2 单击更改身份验证 3 选择组织账户

随机推荐

  • SQL如何比较两个不同表中的两列

    我有两个表 其中表 1 包含 4 列 表 2 包含 8 列 我在 table1 中有两列 我想将它们与 table2 中的两列进行比较 Table 1 have column1 and column2 that needs to be co
  • 由于 PHP 版本,Apache 中的 PHPMyAdmin 500 内部服务器错误

    Version OS lsb release a Ubuntu 18 04 5 LTS PHP php v 8 0 1 Apache apache2 v 2 4 29 Ubuntu MySQL mysql version mysql 版本
  • 如何最小起订量功能

    尝试对其构造函数采用 Func 的类进行单元测试 不知道如何使用 Moq 来模拟它 public class FooBar public FooBar Func
  • 如何防止使用 Git 自动合并?

    我正在尝试将本地分支合并到主分支中 而无需 Git 进行自动合并 我想 手工挑选 我想要合并到 master 中的内容 当我使用 Git 的 difftool 命令时 我可以比较并选择要添加到 master 分支中的内容 但是当我进行合并时
  • 当属性可以抛出异常时对象初始值设定项和 Dispose

    我有以下设置 public class SomeClass private DirectoryEntry root private DirectorySearcher searcher public SomeClass root new D
  • 带有变量赋值的基本 vue.js 2 和 vue-resource http get

    我真的很难让最基本的 REST 功能在 vue js 2 中工作 我想从某个端点获取数据并将返回值分配给我的 Vue 实例的变量 这是我已经走了多远 var link https jsonplaceholder typicode com u
  • .split(/\s+/) 和 .split(" ") 之间的区别?

    首先 抱歉我的英语不好 p 我正在查看下一个 js 代码片段 var classes element className split s 该代码会将 和 元素的完整类名拆分为包含每个类的数组 但是 使用之间有什么区别 split s 并使用
  • 如何正确使用lua_pop()函数?

    谁能告诉我如何在 C 中正确使用 lua pop 函数 当我使用 lua get 函数时我应该调用它吗 喜欢 lua getglobal L 某事 lua pop L 1 或者如何使用它 垃圾收集器会在阈值之后清除这些东西吗 谢谢 你打电话
  • Angular:将 XML 转换为 JSON

    我有这种方法 我从远程服务器接收 XML 响应 我需要将 XML 转换为 JSON 以便 Angular 2 可以处理数据 private extractData res Response let xml res body console
  • 静态图像的OpenCV haar训练

    我尝试训练 haar 级联分类以进行卡片套装检测 没有旋转并且图像没有失真 例如 我有文件 Clubs png 其中包含白色背景 20x20 像素的俱乐部图像 这个教程好纠结http note sonots com SciSoftware
  • Orchard CMS中如何处理来自JS的跨域Web服务调用

    我正在尝试从 HTML 小部件内跨域调用 Web 服务 这似乎不起作用 它在同一域下运行得很好 我正在尝试在 Orchard 中创建一个登录页面 可用于登录另一个域上的我的软件 Web 服务正在验证用户凭据并返回一个布尔值 然后该布尔值将生
  • 无法执行 dex:Eclipse 中超出了 GC 开销限制

    当我下载Git项目时OsmAnd并去编译它 Eclipse 返回这些错误 Dex Loader Unable to execute dex GC overhead limit exceeded OsmAnd Conversion to Da
  • 如何在Windows上安装gssapi python模块?

    我目前正在尝试获取gssapi模块让 python 在 Windows 上运行 我的目标是使用 python 模块通过 Active Directory 进行身份验证ldap3 gssapi 是其工作的必要条件 但是 安装失败 因为找不到
  • 如何从 Visual Studio (2003) 中运行我的 Windows CE 项目?

    我正在开发一个遗留应用程序 需要在 VS 2003 中继续 但是 我无法有效地调试它 因为当我尝试运行它时 我收到以下对话框 Deploy 选择要定位的设备 如果所选设备上尚未安装 NET Compact Framework 它将与您的应用
  • 是否有相当于 GetLastInputInfo / LASTINPUTINFO 的 64 位?

    We use 获取最后输入信息并计算与GetTickCount64结果的差值来确定空闲情况 然而 GetLastInputInfo返回的tick计数被写入LASTINPUTINFO的成员dwTime中 它是一个DWORD 因此是一个无符号3
  • 在 Windows 中设置 stdout/stderr 文本颜色

    我尝试使用system color 24 但这并没有改变提示中的颜色 所以经过更多的谷歌搜索后我看到SetConsoleTextAttribute并编写了以下代码 这导致两者stdout and stderr两者都变成红色而不是stdout
  • 为什么这个 for 循环不处理数组的所有元素?

    给出以下脚本 bin bash asteriskFiles sip conf extensions conf for asteriskFile in asteriskFiles do backup current configuration
  • 如何与窗框碰撞,弹起球并将球限制在矩形区域内?

    嘿 我正在尝试使用 pygame 创建一个突破克隆 并且我使用了 self course 180 self course 360 为了弹起球拍的球 我正在研究向量 2 类 但我不知道如何使用它来转换我的球类 如果有人能引导我走向正确的方向
  • iOS - 照片后台上传

    我想创建一个应用程序 它将自动将相机胶卷中的新照片上传到我的网络服务 就像新的 Flickr 应用程序的自动上传功能一样 目前我正在研究如何正确设置它 我猜 iOs 7 的新后台功能可以实现这一点 但是 是否可以从后台获取启动后台传输服务
  • 支持 dropdownlist .NET MVC 中的 optgroup?

    从这个问题继续以编程方式创建下拉列表我希望我的清单有几个optgroup也列出了 目前这可能吗 我知道我需要将 selectList 传递到 dropDownList 但不知道如何将文本 值 optgroup 添加到 selectList