ASP.NET MVC DropDownListFor,其类型为List <string>

Che*_*hev 47 c# asp.net-mvc html-helper razor asp.net-mvc-3

我有一个类型为List的模型的视图,我想在页面上放置一个下拉列表,其中包含列表中的所有字符串作为下拉列表中的项目.我是MVC的新手,我怎么做到这一点?

我试过这个:

@model List<string>
@Html.DropDownListFor(x => x)
Run Code Online (Sandbox Code Playgroud)

但那引发了一个错误.任何帮助表示赞赏.

Dar*_*rov 121

要制作下拉列表,您需要两个属性:

  1. 要绑定到的属性(通常是整数或字符串类型的标量属性)
  2. 包含两个属性的项目列表(一个用于值,一个用于文本)

在您的情况下,您只有一个字符串列表,无法利用该列表创建可用的下拉列表.

对于数字2,您可以获得值,并且文本与您需要绑定的属性相同.您可以使用辅助函数的弱类型:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)
Run Code Online (Sandbox Code Playgroud)

其中Foo将是ddl的名称,并由默认模型绑定器使用.因此生成的标记可能如下所示:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>
Run Code Online (Sandbox Code Playgroud)

这就是说下拉列表的一个更好的视图模型如下:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)
Run Code Online (Sandbox Code Playgroud)

如果你想在这个列表中预先选择一些选项,你需要做的就是将SelectedItemId这个视图模型的属性设置为集合Value中某个元素的对应元素Items.

  • 这不起作用,你怎么得到控制器上的值Post ... SelectedItemId和Items都是null. (12认同)

Pau*_*hra 6

如果您在下拉列表中有想要的字符串类型列表,我会执行以下操作:

编辑:澄清,使其成为一个更完整的例子。

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })
Run Code Online (Sandbox Code Playgroud)

这给出了一个下拉列表,如下所示:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>
Run Code Online (Sandbox Code Playgroud)

获取控制器帖子上的值;如果您使用具有字符串列表作为属性的模型(例如 MyViewModel),因为您已指定 x => x.ShipNames,您只需将方法签名设为(因为它将在模型中序列化/反序列化):

公共 ActionResult MyActionName(MyViewModel 模型)

像这样访问 ShipNames 值:model.ShipNames

如果您只想访问帖子的下拉列表,则签名变为:

公共 ActionResult MyActionName(string ShipNames)

编辑:根据评论阐明了如何访问模型集合参数中的 ShipNames 属性。