MVC 中的语言下拉菜单

Languages drop down menu in MVC

我想创建一个用于语言选择的下拉菜单。它是一个 MVC 数据库应用程序。我希望用户能够选择多种语言。

我想知道的是如何将我的模型连接到剃须刀视图。我可以在 class 的 属性 上面使用什么样的属性?

这是模型的快照class我有:

public class CrewViewModel
    {
 // This is the date of birth property
        [Required]
        [DisplayName("Date of Birth")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-dd-mm}", ApplyFormatInEditMode = true)]
        public DateTime DOB { get;  
 // Here goes the code for the Languages property
    }

以及在视图中使用什么剃须刀代码。

有很多方法可以做到这一点,我过去通过创建一个特定的 class 来连接我的价值观来做到这一点:

public class LanguageItem
{
    public bool Disabled { get; set; }
    public string Value { get; set; }
    public string Name { get; set; }
}

然后您可以在模型中创建 属性 作为:

public IEnumerable<LanguageItem> Languages
{
    get
    {
         return new List<LanguageItem>
          {
              new LanguageItem {Name = "English", Value = "en-US"}
          };
    }
}

或者无论如何填充你的。为选择创建一个字段(即 SelectedLanguage)。然后像...

 @Html.DropDownListFor(m => m.SelectedLanguage, new SelectList(Model.Languages, "Value", "Text"), "Language")

应该可以