Problem binding enum to dropdownlist

3 posts, 0 answers
  1. Steve
    Steve avatar
    13 posts
    Member since:
    Aug 2008

    Posted 26 Apr 2013 Link to this post

    I am trying to bind an enum to a dropdown list. I am successful using the vanilla @Html.DropDownListFor, but unsuccessful with the @Html.Kendu().DropDownListFor.

    My enum provider is:
    public static IEnumerable<SelectListItem> SexListItems
    {
        get
        {
            foreach (var value in Enum.GetValues(typeof(Sex)))
            {
                string name = string.Format("Sex.{0}", Enum.GetName(typeof (Sex), value));
                var text = Resources.Shared.EnumStrings.ResourceManager.GetString(name);
                yield return new SelectListItem() {Value = value.ToString(), Text = text};
            }
        }
    }


    The following code works well, showing the list and binding to the  property::
    @Html.DropDownListFor(p => p.Sex, DataProviders.SexListItems)


    However, the following displays the list, but does not bind to the property:
                   
    @Html.Kendo().DropDownListFor(p => p.Sex).BindTo(ELSORegistry.DataProviders.SexListItems)

     

     

     


  2. Petur Subev
    Admin
    Petur Subev avatar
    1882 posts

    Posted 30 Apr 2013 Link to this post

    Hello Steven,

    When the field which you want to edit as an enum then we cannot determine whether the value is the string representation or the int representation of that enum.
    For example in your case the SelectListItem value is actually the string (text) representation.
    So you need to specify the value manually by turning the enum value into string.

    e.g.

    @Html.Kendo().DropDownListFor(m=>m.Sex).BindTo(YourProvider.SexListItems).Value(Model.Sex.ToString())


    Kind Regards,
    Petur Subev
    the Telerik team
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. UI for ASP.NET MVC is VS 2017 Ready
  4. Steve
    Steve avatar
    13 posts
    Member since:
    Aug 2008

    Posted 30 Apr 2013 Link to this post

    Many thanks. Petur, it works perfectly. Great product, just having to navigate the learning curve.
Back to Top