c# - 使用 List<Cars> 的下拉列表的 MVC 助手

标签 c# asp.net asp.net-mvc

我的强类型 View 数据中有一个列表集合。

如何使用 Html.DropDownList 助手?

<%= Html.DropDownList(ViewData.Model.Cars) %>

(以上不起作用,似乎与任何签名都不匹配)

这是 MVC2。

最佳答案

如果您的 Car 类看起来像这样

public class Car
{
    public int Id { get; set; }

    public string Name { get; set; }
}

然后你像这样在你的 View 模型上放置一个属性

public int CarId { get; set; }

您生成的 View 模型如下所示

public class YourViewModel
{
    public int CarId { get; set; }

    public List<Car> Cars { get; set; }
}

你可以这样做

this.Html.DropDownListFor(x => x.CarId, new SelectList(this.Model.Cars, "Id", "Name"))

发布时,如果 View 模型是 Action 的参数,CarId 将被绑定(bind)到默认模型绑定(bind)器的边界。

关于c# - 使用 List<Cars> 的下拉列表的 MVC 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9218228/

相关文章:

asp.net - 带有 ASP .NET 的 MySQL 数据库

c# - 使用 ASP.Net MVC 在单个 View 中管理多个查找

asp.net-mvc - 如何在 ASP.NET MVC 中测试 ajax 提交?

c# - 将父窗口设置为 wpf 窗口

c# - OnPropertyChanged 不编译

c# - 我得到 "missing a using directive or assembly reference"并且不知道出了什么问题

c# - GridView 中 DropDownList 的动态名称

asp.net - 在 Azure SQL 上打开 DataReader 错误,但在 SQL Server 2014 上却没有

c# - 使用 TryParse 的猜数字游戏

c# - 在 .net 中读/写雅虎日历(测试版)