在编辑模式下显示 Kendo DropDownListFor 的枚举值

Displaying enum values on Kendo DropDownListFor in Edit mode

我有一个 enum class 并且我在创建模式下将它的值绑定到 Kendo DropDownListFor 没有任何问题。在编辑模式下,这些值也绑定到 Kendo DropDownListFor,但未选择当前值的索引。我的意思是记录的 IdentityTypePassport,但是 DropDownList 显示 "Please Select",就像在创建模式中一样。我该如何解决?

注意: 当使用 @Html.DropDownListFor 而不是 Kendo().DropDownListFor 时它可以工作,但我想通过使用 Kendo().DropDownListFor 来执行此操作。


枚举(身份类型):

public enum IdentityType
{       
    [Description("Identity Card")]
    IdentityCard= 1,
    [Description("Driver License")]
    DriverLicense= 2,
    [Description("Passport ")]
    Passport = 3
}


枚举助手方法:

/// <summary>
/// For displaying enum descriptions instead of enum names on grid, ddl, etc.
/// </summary>
public static string GetDescription<T>(this T enumerationValue)
        where T : struct
{
    Type type = enumerationValue.GetType();
    if (!type.IsEnum)
    {
        throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
    }

    //Tries to find a DescriptionAttribute for a potential friendly name
    //for the enum
    MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    if (memberInfo != null && memberInfo.Length > 0)
    {
        object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attrs[0]).Description;
        }
    }
    //If we have no description attribute, just return the ToString of the enum
    return enumerationValue.ToString();
}


查看:

@(Html.Kendo().DropDownListFor(m => m.IdentityType)
    .HtmlAttributes(new { @class = "k-dropdown" })
    .OptionLabel("Please select").BindTo(Enum.GetValues(
        typeof(Enums.IdentityType)).Cast<Enums.IdentityType>()
    .Select(x => new SelectListItem { Text = x.GetDescription(), Value = x.ToString() }))
)


//This works but I want to perform this by uisng Kendo().DropDownListFor:
@Html.DropDownListFor(x => x.IdentityType, 
    new SelectList(Enum.GetNames(typeof(Enums.IdentityType)), new { @class = "k-dropdown" }))

我遇到了同样的问题,我找到的唯一解决办法是手动设置值:

@(Html.Kendo().DropDownListFor(m => m.IdentityType)
    ...
    .Value(Model.IdentityType.ToString())
)