【问题标题】:enumeration toselectlist with correct value枚举到具有正确值的选择列表
【发布时间】:2017-03-29 04:27:57
【问题描述】:

使用 ASPNET MVC 4,假设我有一个枚举

public enum IndicatorGroup
    {
        Include_ANY_MatchingIndicator = 1,
        Include_ALL_MatchingIndicator = 2,
        Exclude_ANY_MatchingIndicator = 3,
        Exclude_ALL_MatchingIndicator = 4
    };

我使用以下辅助方法将其绑定到下拉列表,如下所述:How do you create a dropdownlist from an enum in ASP.NET MVC?

public static class MyExtensions{
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
            select new { Id = e, Name = e.ToString() };
        return new SelectList(values, "Id", "Name", enumObj);
    }
}

现在我希望选择的值是一个数字(这可能在上面的代码中指定为)

Id = e ,

但是当我获得选定的值时,它会返回文本 Exclude_ALL_MatchingIndicator 而不是数字 4。如何正确设置它?

查看

 @Html.DropDownListFor(m => m.IndicatorGroups, Model.IndicatorGroups.ToSelectList(), new { @id = "ddlIndicatorGroup" })

【问题讨论】:

  • Id = (int)e,但是你为什么要它是一个数字呢?
  • 确实 id = (int)e 但它给出了解析错误。无法将类型 TEnum 转换为 int
  • 我只是想将下拉列表中的值设置为数字和文本作为 Include_ANY_MatchingIndicator 等
  • 使用Id = Convert.ToInt32(e)

标签: c# asp.net-mvc enums


【解决方案1】:

可以使用Convert.ToInt32(e),这样代码就变成了

var values = from TEnum e in Enum.GetValues(typeof(TEnum))
             select new { Id = Convert.ToInt32(e), Name = e.ToString() };
return new SelectList(values, "Id", "Name", Convert.ToInt32(enumObj));

但是,您并不想这样做。如果属性IndicatorGroups 的值是IndicatorGroup.Exclude_ANY_MatchingIndicator,那么您的DropDownListFor() 方法将首先显示第一个选项,因为该属性的值与任何选项值都不匹配。在内部,该方法基于第二个参数构建一个新的IEnumerable&lt;SelectListItem&gt;,如果属性的.ToString() 值与任何SelectListItemValue 属性匹配,则设置Selected 属性 - 在您的情况下为"Exclude_ANY_MatchingIndicator"将不匹配 1234,因此将选择第一个选项(因为必须这样做)。

您已在 cmets 中指示要将所选值保存为数据库中的INT,在这种情况下,在您的 POST 方法中,将绑定值转换为 int。假设您在视图中选择了第二个选项,那么您模型的IndicatorGroups 属性将为IndicatorGroup.Include_ALL_MatchingIndicator。要将值保存为 int,请使用

int valueToSave = (int)model.IndicatorGroups; // returns 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多