简体   繁体   English

如何在DropDownListFor中的模型中设置默认值?

[英]How to set a default value from the model in a DropDownListFor?

I'm using DropDownListFor to create a drop-down of enums. 我正在使用DropDownListFor创建一个枚举的下拉列表。 I am creating an edit profile page that lets the user edit there level, so I want by default to have what they had in their profile selected, just in case they don't want to change that field. 我正在创建一个编辑配置文件页面,该页面允许用户在此处进行编辑,因此默认情况下,我希望选择他们在配置文件中拥有的内容,以防万一他们不想更改该字段。 So if they had sophomore in their profile the drop-down should default to sophomore selected. 因此,如果他们的个人资料为大二,则下拉列表应默认为选择大二。 How do I set the default value to be what was from the model(or the database)? 如何将默认值设置为来自模型(或数据库)的默认值?

I have tried adding an option label like so, but it adds an extra select item, that I don't need. 我尝试像这样添加选项标签,但是它添加了我不需要的额外选择项。 I just need what they already have in the model to be selected. 我只需要选择他们已经在模型中拥有的东西。

@Html.DropDownListFor(x => x.AcademicInfo.ClassLevel, Html.GetEnumSelectList<ClassLevel>(), Model.ClassLevel.ToString())

Model: 模型:

public class ViewModel
{
 [Display(Name = "Class Level")]
 public ClassLevel ClassLevel { get; set; }
}

HTML in View: 视图中的HTML:

@Html.DropDownListFor(x => x.AcademicInfo.ClassLevel, Html.GetEnumSelectList<ClassLevel>())

Enum: 枚举:

public enum ClassLevel
{
    Freshman = 1,
    Sophomore = 2,
    Junior = 3,
    Senior = 4
    //Other = 5
}

How I add it to the model: 如何将其添加到模型中:

ViewModel model = new  ViewModel();
model.ClassLevel = (ClassLevel)latestYear.ClassLevelId;

I need to be able to set a default value from the model 我需要能够从模型中设置默认值

This happens naturally when you map the data onto your view model. 当您将数据映射到视图模型时,自然会发生这种情况。 In other words, if the entity has ClassLevel set to ClassLevel.Sophmore , then you would map that value onto the ClassLevel property on your view model, which will then also be ClassLevel.Sophmore . 换句话说,如果实体的ClassLevel设置为ClassLevel.Sophmore ,则可以将该值映射到视图模型的ClassLevel属性上,该属性将是ClassLevel.Sophmore Then, since you've bound the select to the ClassLevel property, the value of the dropdown will automatically be set to the value of the property, ie ClassLevel.Sophmore in this case. 然后,由于您已将select绑定到ClassLevel属性,因此下拉列表的值将自动设置为该属性的值,在这种情况下为ClassLevel.Sophmore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM