在ASP.NET MVC 2中实现DropDownList的最佳方式是什么?

12

我正在尝试了解在ASP.NET MVC 2中使用DropDownListFor助手实现 DropDownList 的最佳方法。 这是一个多部分问题。

首先,传递列表数据到视图的最佳方式是什么?

  1. 将包含数据的SelectList属性与模型一起传递
  2. 通过ViewData传递列表

如何在DropDownList中获取空值? 我应该在创建SelectList时将其构建到其中,还是有其他方法告诉助手自动创建空值?

最后,如果由于某种原因出现服务器端错误,需要重新显示带有DropDownList 的屏幕,是否需要重新获取列表值以传递到视图模型中? 这些数据在提交后不会被保留(至少不是通过模型传递),所以我打算再次获取它(已缓存)。这样做正确吗?

5个回答

9

1
使用ViewData的问题是它让您的控制器变得更难测试。如果您将所有内容都保留在ViewModel中,您的测试效果会更好。 - Mac
2
实际上并没有任何区别 - 使用ViewModel时,您必须探索ViewData.Model,否则您只需使用键请求它。完全没有区别... - user1151

3

分部回答:

  1. The best way IMHO is to pass the list in the ViewModel like this:

    public SelectList Colors
    {
        get
        {
            // Getting a list of Colors from the database for example...
            List<Color> colors = GetColors().ToList();
    
            // Returning a SelectList to be used on the View side
            return new SelectList(colors, "Value", "Name");
        }
    }
    
  2. To get a blank or default option like ( -- Pick a color -- ), you can do this on the view side:

    @Html.DropDownListFor(m => m.Color, Model.Colors, "-- Pick a color --")
    
  3. You'll have to fetch/populate the list again if it's part of the ViewModel.


请看以下博客文章,它可以给你一些提示:

下拉列表和ASP.NET MVC


2
你可以这样做:

您可以像这样操作:

<%= Html.DropDownListFor((x => x.ListItems), Model.ListItems, "")%>

或者

<%= Html.DropDownList("ListItems", Model.ListItems, "")%>

最后一个参数“optionLabel”会生成一个空的列表项。
在这种情况下,您可以看到ListItems是模型的属性。
我还将视图强类型化为该模型。

0

我发现使用 SelectListItems 序列(而不是 SelectList)更直观。

例如,这将从客户对象序列创建一个 IEnumerable<SelectListItem>,您可以将其传递给 Html.DropDownListFor(...) 帮助程序。'Selected' 属性将可选地设置下拉列表中的默认项。

var customers = ... // Get Customers
var items = customers.Select(c => new SelectListItem
                             {
                                 Selected = (c.Id == selectedCustomerId),
                                 Text = c.Email,
                                 Value = c.Id.ToString()
                             }); 

0

(你已经知道了!)

  1. 将包含数据的 SelectList 属性的列表传递到您的模型中

是的,在构建 SelectList 时添加它。(如果使用 LINQ 构建列表,Union 可能会有用。)

是的,要做,而且是的,你就是。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接