SelectListItem 中的选定属性永远不起作用 (DropDownListFor)

2024-03-13

我在选择 DropDownList 的值时遇到问题。我一直在阅读所有类似的帖子,但找不到解决方案。

实际的方法对我来说似乎非常好,因为我可以检查 SelectList 内的字段:

var selectList = new List<SelectListItem>(
    from variable in someKindOfCollection
    select new SelectListItem
        {
            Selected = variable.Property == selection,
            Text = variable.Property,
            Value = variable.Property
        });

据说,这给了我完全的控制权。构建 selectList 后,我​​可以使用调试器检查变量。一切正常,其中之一已标记为“选定”属性。

然后我使用 DropDownListFor 以便在视图上显示:

@Html.DropDownListFor(
    g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })

但它不起作用,永远不会...“渲染”下拉列表,但没有选择任何内容。

多谢 :)

新例子 首先我想道歉。我一直在隐藏信息,当然完全是无意的。 所有代码都发生在 Razor For 循环内:

@foreach (var loopVariable in Model.Collection)
{
    if (Model.SomeCondition != null)
    {
        selection = someValue;
    }

    var selectList = new List<SelectListItem>(
      from variable in someKindOfCollection
      select new SelectListItem
    {
        Selected = variable.Property == selection,
        Text = variable.Property,
        Value = variable.Property
    });

    @Html.DropDownListFor(
        g => g.SomePropertyInModel , selectList, new { @class = "cssClass" })

}

那么, selectList 是一个局部变量导致了这种行为吗?抱歉,我没想到是这样的。


我想你也遇到了和我一样的问题。我查看了源代码来找到我的解决方案,看来这对我来说是一个错误。下面的 DropDownListFor 应该有所帮助,关键是将选定的值传递到 html 帮助器中。希望这可以帮助。

public static class SelectExtensions {
    public static IHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string selectedValue, string optionLabel, object htmlAttributes = null) {
       return DropDownListHelper(helper, ExpressionHelper.GetExpressionText(expression), selectList, selectedValue, optionLabel, htmlAttributes);
    }

    /// <summary>
    /// This is almost identical to the one in ASP.NET MVC 3 however it removes the default values stuff so that the Selected property of the SelectListItem class actually works
    /// </summary>
   private static IHtmlString DropDownListHelper(HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, string selectedValue, string optionLabel, object htmlAttributes) {
        name = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

        // 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 SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }, selectedValue));

        // Add the other options
        foreach (var item in selectList) {
            listItemBuilder.AppendLine(ListItemToOption(item, selectedValue));
        }

        // Now add the select tag
        var tag = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() };
        tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        tag.MergeAttribute("name", name, true);
        tag.GenerateId(name);

        // If there are any errors for a named field, we add the css attribute
        ModelState modelState;

        if (helper.ViewData.ModelState.TryGetValue(name, out modelState)) {
            if (modelState.Errors.Count > 0)
                tag.AddCssClass(HtmlHelper.ValidationInputCssClassName);
        }

        // Add the unobtrusive validation attributes
        tag.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(name));

        return tag.ToHtmlString(TagRenderMode.Normal);
    }

    private static string ListItemToOption(SelectListItem item, string selectedValue) {
        var tag = new TagBuilder("option") { InnerHtml = HttpUtility.HtmlEncode(item.Text) };

        if (item.Value != null)
            tag.Attributes["value"] = item.Value;

        if ((!string.IsNullOrEmpty(selectedValue) && item.Value == selectedValue) || item.Selected)
            tag.Attributes["selected"] = "selected";

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

SelectListItem 中的选定属性永远不起作用 (DropDownListFor) 的相关文章

随机推荐

  • MySQL - 如何规范化包含分隔符分隔 ID 的列

    我正在尝试规范化一个表 该表是以前的开发人员设计的 其中有一列包含管道分隔的 ID 这些 ID 链接到同一个表中的其他行 客户表 id aliases VARCHAR 1 4 58 76 2 3 4 1 58 76 58 1 4 76 76
  • 在集合中的项目数非常大的 WHERE 子句中使用“IN”

    我遇到一种情况 我需要对一组非常大的行进行更新 我只能通过它们的 ID 来识别这些行 因为目标记录是由用户选择的 除了用户的记录集之外没有任何共同点 想修改 所有这些记录上的相同属性都在更新 因此我想进行一次 UPDATE 调用 这是不好的
  • HOG 人体检测器:背景减除图像的误报检测

    我正在开展一个需要检测场景中的人员的项目 最初在原始帧上运行 HOG 检测器后 所有帧上的特定背景对象都被检测为人 从而产生 3021 个误报检测 因此 我采取了合理的步骤 通过对所有帧应用背景减法器 BackgroundSubtracto
  • Rascal:创建 AST 时 boolcollectBindings 的作用是什么?

    我有一个关于在 rascal 中创建 AST 的问题 我通常会执行以下操作 model createM3FromEclipseProject project testproject decls createAstsFromEclipsePr
  • PHP preg_match 长度限制 3276

    看来 PHP 的preg match在某些情况下 匹配重复字符的字符数限制为 3276 i e s 0 3276 有效 但是 s 0 3277 才不是 它似乎并不总是适用 因为 0 3277 works 我在 PHP 文档或错误跟踪器中找不
  • 在距离 10 的圆内画一个圆

    我最近开始使用 Android 我需要在圆内画一个圆 就像下面的图片一样 距离 10 如果你看到下面的照片 我需要画一个像下面这样的具有两个直径的圆 但我不这样做不需要照片上当前存在的任何图标 只是具有两个直径的圆中的圆 我只想绘制圆圈和两
  • 如何更改Android中全息主题的菜单项文本颜色?

    我在我的应用程序中使用 Theme Holo 我使用以下 Style xml 自定义了我的主题
  • mysqli 或 PDO - 优缺点是什么? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 如何使用 sudo 执行 bash 函数?

    我尝试导出该函数 然后使用 bash 执行它 但这不起作用 export f my func sudo bash c my func bash my func command not found 如果我尝试在不使用 sudo 的情况下使用
  • 组合 2 个列表的元素

    假设我们有两个列表 val l1 List a b c val l2 List 1 2 3 我想要的是 List a1 b2 c3 即 将 l1 的第 n 个元素与 l2 的第 n 个元素相加 实现它的一种方法是 l1 zip l2 map
  • Runtime.exec().waitFor() 实际上并未等待

    我有一些使用 Runtime exec 运行外部 jar 作为 IzPack 安装程序构建 的代码 如果我从命令行运行这个 external jar 如下所示 java jar external jar 然后 在应用程序完成之前 命令提示符
  • XCode:添加构建阶段被禁用

    我想添加崩溃解决方案 https www crashlytics com我的 iOS 项目需要添加插件Run script阶段 但无论我做什么 为了添加构建阶段所有选项均被禁用 我选择目标 gt 构建阶段 我有合适的方案 我的项目运行良好
  • 操作系统如何在屏幕上绘制窗口?

    经过多年的计算机使用和编程 我意识到实际在屏幕上绘制的软件堆栈对我来说基本上是一个谜 我曾研究过一些嵌入式 LCD GUI 应用程序 我认为这为简化堆栈提供了一些线索 但对于 Windows 操作系统之类的东西的整体情况仍然模糊 据我所知
  • Spring WebClient:SSLEngine 已关闭

    我们使用 Spring boot 版本 2 3 1 也使用 WebClient 我的网络客户端配置 private val client WebClient init val sslCtx SslContextBuilder forClie
  • Octave无法安装图像采集包

    根据相关的维基页面 http wiki octave org Image acquisition package http wiki octave org Image acquisition package 安装您输入的图像采集包 pkg
  • Git 和 GitHub Desktop 是完全独立的应用程序吗?

    几个月前 我在 Windows 7 计算机上安装了适用于 Windows 的 GitHub Desktop 版本 2 8 2 x64 我使用 GitHub Desktop 在本地计算机和 GitHub 云之间管理用 LaTeX 编写的论文版
  • 如何在 networkX 图中弯曲边缘

    I had previous asked this question https stackoverflow com questions 63918432 curved edges in networkx on how to achieve
  • 在 OS X 10.5 上使用 readline 的 rl_insert_text

    因此 我尝试使用 readline 将一些默认文本填充到用户输入中 但无法使其在 OSX 10 5 上工作 rl insert text ex c gcc o rl insert text ex rl insert text ex c lr
  • PHP 5.3 之前的数组中的闭包对象

    我知道可以使用 PHP 5 3 匿名函数 执行以下操作 但是在较旧的 PHP 版本 5 3 之前 中是否有类似的替代方法 exampleArray array func gt function echo this is an example
  • SelectListItem 中的选定属性永远不起作用 (DropDownListFor)

    我在选择 DropDownList 的值时遇到问题 我一直在阅读所有类似的帖子 但找不到解决方案 实际的方法对我来说似乎非常好 因为我可以检查 SelectList 内的字段 var selectList new List