ASP.NET MVC DropDownListFor 模型类型为 List<string> [英] ASP.NET MVC DropDownListFor with model of type List&lt;string&gt;

查看:24
本文介绍了ASP.NET MVC DropDownListFor 模型类型为 List<string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

我试过了:

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

但这引发了错误.

推荐答案

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

To make a dropdown list you need two properties:

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

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

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

对于数字 2,您可以让值和文本相同,您需要绑定到一个属性.您可以使用弱类型版本的帮助程序:

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

其中 Foo 将是 ddl 的名称,并由默认模型绑定器使用.所以生成的标记可能看起来像这样:

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

然后:

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

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

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.

这篇关于ASP.NET MVC DropDownListFor 模型类型为 List<string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆