如何在编辑记录中为EnumDropDownListFor属性设置保存的值

时间:2015-05-20 10:12:15

标签: c# asp.net-mvc asp.net-mvc-4 enums

我为血型创造了Enum。

我有一个问题,就是如何设置我从控制器中血型字段的数据库获取的值。如何在控制器的编辑操作中为 Enum_Member_BloodGroup =?设置值。

我在 s.BloodGroup

中获取数据
  

枚举

public enum bloodGroup
{
        [Display(Name = "A +ve")]
        Apositive = 1,
        [Display(Name = "B +ve")]
        BPostive,
        [Display(Name = "AB +ve")]
        ABPositive,
        [Display(Name = "O +ve")]
        OPositive,
        [Display(Name = "A -ve")]
        ANegative,
        [Display(Name = "B -ve")]
        BNegative,
        [Display(Name = "AB -ve")]
        ABNegative,
        [Display(Name = "O -ve")]
        ONegative
}
  

模型

public class EditStudentViewModel
{
    [DisplayName("Blood Group")]
    public clsEnums.bloodGroup Enum_Member_BloodGroup { get; set; }
  

控制器

[HttpGet]
    public ActionResult Edit(int id = 0)
    {
        try
        {

            using (TakshShilla_SchoolEntities objConnection = new TakshShilla_SchoolEntities())
            {
                var str = (from s in objConnection.tblStudents
                           where s.Student_ID == id
                           select new EditStudentViewModel
                           {
                               Student_ID = s.Student_ID,
                               FullName = s.FullName,
                               Standard = s.Standard,
                               RollNo = s.RollNo,                                  

                               Enum_Member_BloodGroup = 
  

查看

<div class="form-group">
    @Html.LabelFor(model => model.Enum_Member_BloodGroup, new { @class = "control-label col-md-3" })
    <div class="col-md-9">
        @Html.EnumDropDownListFor(model => model.Enum_Member_BloodGroup, "--Select--")                               
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

在配置之前,您必须将来自数据库的int值明确地转换为Enum类型,并且在视图中,它将由html帮助程序自动选择。

这样做:

select new EditStudentViewModel
           {
              Student_ID = s.Student_ID,
              FullName = s.FullName,
              Standard = s.Standard,
              RollNo = s.RollNo,                                  
              Enum_Member_BloodGroup = (clsEnums.bloodGroup)s.BloodGroup