c# - 在 MVC 5 中正确设置 DropDownListFor

标签 c# asp.net-mvc entity-framework asp.net-mvc-4 asp.net-mvc-5

我使用 ADO.NET Entity Framework 将数据库映射到应用程序中的模型。我已经设置了 ViewModel 进行注册,如下所示:

public class UserRegistrationViewModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string PasswordConfirm { get; set; }
        public SelectList Countries { get; set; }

    }

这里的具体部分是我想用 DBContext 中的国家/地区填充下拉列表,如下所示:

Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();

正如您所看到的,国家/地区现在是一个列表,在我看来,我想使用 Html 帮助器类设置一个下拉列表,如下所示:

  @Html.DropDownListFor(model => model.Countries);

这就是我在 View 中映射模型的方式:

@model WebApplication2.ViewModels.UserRegistrationViewModel

如何正确设置下拉列表(即选择列表)以便可以显示数据库中的数据?

最佳答案

您需要两个属性:一个用于保存所选值,另一个用于保存选择列表选项:

public string Country { get; set; }

public IEnumerable<SelectListItem> CountryOptions { get; set; }

那么,在你看来:

@Html.DropDownListFor(m => m.Country, Model.CountryOptions)

您不需要实际的SelectList。事实上,如果不这样做更好。 Razor 将自动创建一个 SelectList 并选择适当的值。

关于c# - 在 MVC 5 中正确设置 DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286518/

相关文章:

entity-framework - 如何获取 EntityFramework NuGet 包的 PDB 文件?

entity-framework - 如何通过MsDeploy在发布时迁移Entity Framework DB

c# - 初始化 Entity Framework 上下文的最佳方法?

c# - jQuery AJAX 的 ASP.Net MVC 路由问题

asp.net-mvc - 如何在 ASP.NET MVC 2 中执行 "causesvalidation=false"?

c# - Visual Studio 的 C# 自动事件处理程序生成。为什么它要创建一个新的委托(delegate)?

c# - 将 JSON 对象传递给 MVC

javascript - Kendo MVC NumericTextBoxFor 默认值未绑定(bind)到模型

c# - Respawn 没有重置我的 SQL Server 数据库

c# - PowerShell 排序顺序不正确