Search code examples
asp.net-mvcenumskendo-uikendo-asp.net-mvckendo-dropdown

Displaying enum values on Kendo DropDownListFor in Edit mode


I have an enum class and I bind its values to Kendo DropDownListFor in Create mode without any problem. In Edit mode, these values are bound to Kendo DropDownListFor as well, but the current value's index is not selected. I mean that the record's IdentityType is Passport, but DropDownList shows "Please Select" as in Create mode. How can I fix it?

Note: When using @Html.DropDownListFor instead of Kendo().DropDownListFor it works, but I want to perform this by using Kendo().DropDownListFor.


Enum (IdentityType):

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


Enum Helper Method:

/// <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();
}


View:

@(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" }))

Solution

  • I faced same problem, and the only solution i found is to set manually value:

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