我使用 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/