【问题标题】:SelectExtensions.DropDownList resets SelectListItem's Selected propertySelectExtensions.DropDownList 重置 SelectListItem 的 Selected 属性
【发布时间】:2012-02-12 13:47:59
【问题描述】:

我在使用 SelectExtension 的 DropDownList 方法时发现了一个奇怪的行为。我创建了一个 IEnumerable ,其中一个的 Selected 属性设置为“true”。但是,当我将它传递给以下方法时,Selected 属性被重置为“false”,因此下拉控件没有选择正确的项目。

public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable selectList);

我什至尝试过使用 SelectList 类并指定 SelectedValue 属性,但仍然没有选择正确的

关于如何保持所选值的任何想法?

写了 HACK 但更喜欢解决方案

以下是在使用从 MVC 发出的 Html 之前更改所选选项的代码破解。我不喜欢这个解决方案,但我不知道该怎么做。

// the following is a hack due to a precived MVC 3 bug
var html = SelectExtensions.DropDownList(helper, propertyName, source).ToHtmlString();
html = html.Replace("selected=\"selected\"", string.Empty);
html = html.Replace(string.Format("value=\"{0}\"", source.SelectedValue), string.Format("value=\"{0}\" selected=\"selected\"", source.SelectedValue));

【问题讨论】:

  • 你是如何使用这个助手的?展示由您的模型结构、控制器和操作组成的完整示例,这将使我们对您的问题有更多的了解。目前你的问题对我来说毫无意义。

标签: asp.net-mvc-3 selectlistitem


【解决方案1】:

框架会忽略您选择的值,因为它会查看 html.ViewData 并找到与您的下拉列表名称匹配的键(在本例中为 propertyName)并尝试使用那里的值。

一种解决方案是在创建 DropDownList 之前更改 html.ViewData。在你的情况下,是这样的:

html.ViewData[propertyName] = source.SelectedValue;

一个更通用的例子:

html.ViewData['name of your DDL'] = 'The real value you want selected';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多