【问题标题】:Setting up properly DropDownListFor in MVC 5在 MVC 5 中正确设置 DropDownListFor
【发布时间】:2017-03-10 06:00:50
【问题描述】:

我使用 ADO.NET 实体框架将我的数据库映射到我的应用程序中的模型。我已经设置了我的 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);

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

@model WebApplication2.ViewModels.UserRegistrationViewModel

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

【问题讨论】:

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


    【解决方案1】:

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

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

    那么,在你看来:

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

    您不需要实际的SelectList。事实上,如果你不这样做,那就更好了。 Razor 会自动创建一个SelectList 并选择合适的值。

    【讨论】:

    • 我如何用我的数据库中的实际记录填充国家选项? :D 我不能使用简单地将所有记录转换为列表的方法 lol
    • 您只需将它们选择到SelectListItems 的集合中,即db.Countries.Select(m =&gt; new SelectListItem { Value = m.Iso2, Text = m.Name })。 (显然,您会将属性名称更改为 Country 实体上的实际名称。)
    【解决方案2】:

    在您的 viewModel 中添加一个属性来保存所选国家/地区的 id:

    public class UserRegistrationViewModel
    {
        //
        public int SelectedCountryId { get; set; }
        public SelectList Countries { get; set; }
    
    }
    

    我猜你在设置 Country 属性时正在做这样的事情:

    var countries=Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
    //...
    viemodel.Countries=new SelectList(countries, "CountryId", "CountryName");
    

    那么在您看来,您可以执行以下操作:

    @Html.DropDownListFor(model => model.SelectedCountryId, Model.Countries)
    

    【讨论】:

    • 嘿,当我尝试此方法时,它向我显示此错误:'System.Data.Entity.DynamicProxies.Countries_72FA95A5B14211F073C8C11B1E3587265F1CE9063C9540E555C16AC7031F4887' 不包含名为 'Id' 的属性。
    • 您所在国家/地区实体的 PK 是什么?
    • CountryId替换Id
    • 像魅力一样工作!谢谢:) :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多