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

时间:2015-12-29 08:08:52

标签: asp.net-mvc enums kendo-ui kendo-asp.net-mvc kendo-dropdown

我有一个enum类,我在创建模式下将其值绑定到Kendo DropDownListFor没有任何问题。在“编辑”模式下,这些值也会绑定到Kendo DropDownListFor,但不会选择当前值的索引。我的意思是记录IdentityTypePassport,但DropDownList显示"请选择"与创建模式一样。我该如何解决?

注意:使用@Html.DropDownListFor代替Kendo().DropDownListFor时,它有效,但我希望使用Kendo().DropDownListFor执行此操作。


枚举(IdentityType):

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


Enum Helper方法:

/// <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" }))

1 个答案:

答案 0 :(得分:1)

我面临同样的问题,我找到的唯一解决方案是手动设置值:

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