ASP.. NET MVC DropDownListFor与类型为List模型

本文关键字:List string 模型 类型 NET MVC DropDownListFor ASP | 更新日期: 2023-09-27 17:50:26

我有一个模型类型为List<string>的视图,我想在页面上放置一个下拉列表,其中包含列表中的所有字符串作为下拉列表中的项。我是新的MVC,我将如何完成这一点?

我试过了:

@model List<string>
@Html.DropDownListFor(x => x)

ASP.. NET MVC DropDownListFor与类型为List<string>模型

创建下拉列表需要两个属性:

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

在你的情况下,你只有一个字符串列表,不能被利用来创建一个可用的下拉列表。

而对于第二个。您可以让值和文本与需要绑定到的属性相同。您可以使用弱类型版本的帮助器:

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

,其中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>

对于下拉列表来说,一个更好的视图模型是:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

然后:

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

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

如果你有一个字符串类型的List,你想在下拉列表中,我做以下操作:

EDIT:澄清,使其成为一个更完整的示例。

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" })

给出如下的下拉列表:

<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>

获取controller post上的值;如果你正在使用一个模型(例如MyViewModel),它有字符串列表作为属性,因为你已经指定了x =>x.ShipNames您只需将方法签名为(因为它将在模型中被序列化/反序列化):

public ActionResult MyActionName(MyViewModel model)

像这样访问ShipNames值:ShipNames

如果你只是想在post上访问下拉列表,那么签名变成:

public ActionResult MyActionName(string ShipNames)

EDIT:按照注释已经澄清了如何访问模型集合参数中的ShipNames属性

我知道这个问题很久以前就被问过了,但我来这里寻找答案,我所能找到的任何东西都不满意。我终于在这里找到了答案:

https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

要从表单中获取结果,使用FormCollection,然后按模型名拉出每个单独的值,如下所示:

yourRecord.FieldName = Request.Form["FieldNameInModel"];

据我所知,它绝对没有区别你给FormCollection - use请求的参数名称。Form["NameFromModel"]来检索它

不,我没有挖到下面去看看这些魔法是如何在被子下工作的。我只知道它是有效的…

我希望这篇文章能帮助大家避免我在尝试不同的方法之前花费的时间。