如何使用@DropDownListFor获取枚举值的ID?

时间:2019-03-12 19:04:36

标签: asp.net-mvc

我创建了一个枚举,并且值具有ID,现在我需要在@ Html.DropDownListFor中获取ID,但我不知道该怎么做。

如何获取Enum的ID?

枚举

public enum GainLosses
{
    Gain = 1,
    Loss = 2
};

模型

//Gain/Loss
    [DisplayName("Gain/Loss")]
    public int gainLoss { get; set; }
    public IEnumerable<SelectListItem> gainLosses
    {
        get { return CustomEnum.Enum.GetItems<GainLosses>().Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() }); }
    }
    //    

HTML

<div class="form-group">
                        <label for="@Html.IdFor(model => model.gainLoss)" class="cols-sm-2 control-label">Gain/Loss <img src="~/Imagens/required.png" height="6" width="6" title="requerido"></label>
                        @Html.DropDownListFor(model => model.gainLoss, Model.gainLosses, new { Class = "form-control" })
                        @Html.ValidationMessageFor(model => model.gainLoss, "", new { @class = "text-danger" })                        
                    </div><!--/Gain/Loss-->

1 个答案:

答案 0 :(得分:1)

我已经解决了问题。

application/json