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

How to set saved value for EnumDropDownListFor property in edit record

我已经为血型创建了枚举。

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

我正在 s.BloodGroup

中获取数据

Enum

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
}

Model

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

Controller

[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 = 

View

<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>

您必须在分配之前将来自数据库的 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