【问题标题】:Why does this render as a list of "System.Web.Mvc.SelectListItem"s?为什么这会呈现为“System.Web.Mvc.SelectListItem”的列表?
【发布时间】:2010-06-09 18:43:08
【问题描述】:

我正在尝试使用从属性中提取的值填充 DropDownList,而我现在的最终结果是一个只有“System.Web.Mvc.SelectListItem”的列表。我确定我在这里省略了一些小步骤,但对于我的生活,我无法弄清楚它是什么。

生成列表的属性 GET:

public IEnumerable<SelectListItem> AllFoo {
    get {
        var foo = from g in Bar
                  orderby g.name
                  select new SelectListItem {
                     Value = g.fooid.ToString(),
                     Text = g.name
                  };

        return foo.AsEnumerable();
    }
}

控制器代码:

public ActionResult Edit(string id) {
    // n/a code
    ViewData["fooList"] = new SelectList(g.AllFoo, g.fooid);

    return View(g);
}

查看代码:

<%= Html.DropDownListFor(model => model.fooid, ViewData["fooList"] as SelectList) %>

【问题讨论】:

    标签: c# asp.net-mvc linq-to-sql


    【解决方案1】:

    这里的问题是你不应该用IEnumerable&lt;SelectListItem&gt; 填充SelectList。使用SelectListIEnumerable&lt;SelectListItem&gt;,但不能同时使用。更多详情,请看这个问题:Asp.Net MVC 2 Dropdown Displaying System.Web.MVC.SelectListItem

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。您应该在视图中呈现您的列表,例如

      @Html.DropDownListFor(model => model.fooid, new 
          SelectList(ViewData["fooList"],"Text","Value", Model.DefaultValue))
      

      这是基于带有剃刀视图的c#

      【讨论】:

        【解决方案3】:

        编辑:这个问题与已经提出的问题非常相似:

        ASP.NET MVC 2 - Html.DropDownListFor confusion with ViewModel


        否则,您可能会发现这篇文章很有帮助:

        http://www.nickriggs.com/posts/rendering-and-binding-drop-down-lists-using-asp-net-mvc-2-editorfor/

        它使用 EditorFor,但同样可以用于 DisplayFor。

        【讨论】:

        • 这不是很有帮助。这个问题询问为什么
        • 是的,这些其他问题或文章都与这篇文章“非常相似”。事实上根本没有。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        相关资源
        最近更新 更多