ASP.NET MVC DropDownListFor 模型类型为 List

发布于 2024-11-02 06:39:16 字数 235 浏览 1 评论 0原文

我有一个带有 List 类型模型的视图,我想在页面上放置一个下拉列表,其中包含列表中的所有字符串作为下拉列表中的项目。我是 MVC 新手,我该如何实现这一目标?

我尝试了这个:

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

但这引发了错误。

I have a view with a model of type List<string> and I want to place a drop down list on the page that contains all strings from the list as items in the drop down. I am new to MVC, how would I accomplish this?

I tried this:

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

but that threw an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

π浅易 2024-11-09 06:39:16

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

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

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

而对于数字 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

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

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

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

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

This being said a far better view model for a drop down list is the following:

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

and then:

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

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

隐诗 2024-11-09 06:39:16

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

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

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>

To get the value on a controllers post;如果您使用的模型(例如 MyViewModel)具有字符串列表作为属性,因为您已指定 x =>; x.ShipNames 您只需将方法签名设置为(因为它将在模型中序列化/反序列化):

公共 ActionResult MyActionName(MyViewModel 模型)

访问 ShipNames 值,如下所示:model.ShipNames

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

公共 ActionResult MyActionName(string ShipNames)

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

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

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

Which gives a drop down list like so:

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

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

陪你搞怪i 2024-11-09 06:39:16

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

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

要从表单中获取结果,请使用 FormCollection,然后通过其模型名称提取每个单独的值:

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

据我所知,您为该表单指定的参数名称绝对没有区别FormCollection - 使用 Request.Form["NameFromModel"] 检索它。

不,我并没有深入了解魔法在幕后是如何运作的。我只知道它有效......

我希望这可以帮助人们避免在我开始工作之前尝试不同方法的时间。

I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:

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

To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:

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

As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.

No, I did not dig down to see how th4e magic works under the covers. I just know it works...

I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文