5

我有这个来填充 ASP.NET MVC 视图中的下拉列表。

<%= Html.DropDownListFor(model => model.Bikes,
      Model.Bikes.Select(
      x => new SelectListItem {
               Text = x.Name,
               Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
               Selected = x.ID == Model.ID,
           })) %>

调试这个我可以看到该Selected属性设置为true应该的时间。但是当视图被渲染时,列表中的选项都没有被选中。我意识到这可以通过另一个重载来完成,DropDownListFor但我真的想让这个版本正常工作。

有任何想法吗?

4

2 回答 2

5

您选择的值不起作用的原因是因为您使用 Urls 作为选项值但Model.IDSelected子句中指定。

试试这样:

<%= Html.DropDownListFor(
    model => model.Bikes,
    new SelectList(Model.Bikes, "Id", "Name", Model.ID)
)%>

"Id"表示将用作选项值"Name"的属性,而表示将用作选项标签的属性。

如果你想保留Url.Action你可以尝试:

<%= Html.DropDownListFor(
    model => model.Bikes,
    new SelectList(Model.Bikes.Select(x => new {
        Id = x.Id,
        Name = Url.Action("Details", "Bike", new { bikeId = x.ID })
    }), "Id", "Name", Model.ID)
)%>

您会注意到我已经颠倒了 Name 和 Id,因为使用模型 Id 作为选项值似乎更合乎逻辑。


更新:

这不起作用的原因是因为您绑定到(助手IEnumerable的第一个参数)。DropDownListFor当您使用同一个model.Bikes集合时,它应该是一个标量属性:

<%= Html.DropDownListFor(
    model => model.SelectedBikeValue,
    Model.Bikes.Select(
        x => new SelectListItem {
                 Text = x.Name,
                 Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
                 Selected = x.ID == Model.ID,
        }
)) %>

我关于不使用 Urls 作为选项值的评论是正确的。

于 2010-07-28T11:33:53.640 回答
0

我在这个概念上遇到了很多麻烦。当您无法从包含对象中该属性的模型中传递“名称”属性时,它尤其会表现出来,因为这样的对象名称会自动添加到名称之前。这太疯狂了。在浪费了很多时间试图弄清楚这一点之后,我放弃了,写了我自己的下拉扩展,我在这里发布。它非常简单,而且效果很好。

    public static MvcHtmlString SimpleDropDown(this HtmlHelper helper, object attributes, IEnumerable<SelectListItem> items, bool disabled = false)
    {
        XElement e = new XElement("select",
            items.Select(a => {
                XElement option = new XElement("option", a.Text);
                option.SetAttributeValue("value", a.Value);
                if (a.Selected)
                    option.SetAttributeValue("selected", "selected");
                return option;
            })
            );

        if (attributes != null)
        {
            Dictionary<string, string> values = (from x in attributes.GetType().GetProperties() select x).ToDictionary(x => x.Name, x => (x.GetGetMethod().Invoke(attributes, null) == null ? "" : x.GetGetMethod().Invoke(attributes, null).ToString()));
            foreach(var v in values)
                e.SetAttributeValue(v.Key, v.Value);
        }

        if (disabled)
            e.SetAttributeValue("disabled", "");

        return new MvcHtmlString(e.ToString());
    }

另外,我将 flag disabled作为一个额外的参数,因为如果你想通过标准的匿名属性列表绑定到它,这可能会很麻烦。

以下是我目前如何使用它的示例。我将字典翻译成 SelectListItem 的列表,但它可以只是一个简单的列表。

@Html.SimpleDropDown(new { id="EOM", name = "EOM", @class = "topBox" }, Model.EOM.Select(x => new SelectListItem { Text = x.Value, Value = x.Key.ToString(), Selected = Model.EOM.Selected == x.Key }), !Model.EOM.Available)
于 2013-09-20T12:05:18.830 回答