ASP.NET MVC DropDownListFor类型列表与LT车型;串> [英] ASP.NET MVC DropDownListFor with model of type List<string>

查看:114
本文介绍了ASP.NET MVC DropDownListFor类型列表与LT车型;串>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List类型的模型的视图,我希望把一个下拉列表,其中包含从列表中下拉项的所有字符串在页面上。我是新来的MVC,我将如何做到这一点?

I have a view with a model of type List 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)

但抛出一个错误。任何帮助是AP preciated。

but that threw an error. Any help is appreciated.

推荐答案

要做出一个下拉列表,你需要两个属性:

To make a dropdown list you need two properties:


  1. 属性要在其中绑定到
  2. (整型或字符串的通常是一个标量属性)
  3. 包含两个属性(一个是价值观,一个是文本)的项目清单

  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.

虽然数字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"
    )
)

其中,将是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")
)

如果你在这个列表想preSELECT一些选项,所有你需要做的是设置此视图模型到相应的<中的 SelectedItemId 属性code>值在产品一些元素集合。

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类型列表与LT车型;串&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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