【问题标题】:How to set saved value for EnumDropDownListFor property in edit record如何在编辑记录中设置 EnumDropDownListFor 属性的保存值
【发布时间】:2015-05-20 10:12:15
【问题描述】:

我为血型创建了枚举。

我有一个问题,即如何设置我从数据库中为控制器中的血型字段获取的值。如何在控制器的编辑操作中设置 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>

【问题讨论】:

  • 如果它来自模型属性,它应该由助手设置为自动选择

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


【解决方案1】:

您必须在分配之前将来自数据库的 int 值显式转换为您的 Enum 类型,并且在 View 中它将被 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

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2016-04-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多