This is a migrated thread and some comments may be shown as answers.

Value DataTextField with DataAnnotations

1 Answer 105 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
Dario
Top achievements
Rank 1
Veteran
Dario asked on 04 May 2020, 03:01 PM

I have a comboBox

@(Html.Kendo().ComboBox()
                    .Name("contactTypeDropDownList")
                    //.DataTextField("Type") ??
                    //.DataValueField("Type") ??
                    .DataSource(source =>
                    {
                            source.Read(read =>
                            {
                                read.Action("GetContactTypes", "ListBox");
                            })
                            .ServerFiltering(true);
                    })
                    .SelectedIndex(0)

 

the action returns items of enum

public IActionResult GetContactTypes()
{
    var contactTypes = new List<ContactTypes>();
 
    contactTypes.Add(ContactTypes.Company);
    contactTypes.Add(ContactTypes.Person);
 
    return Json(contactTypes);
}

 

this enum contains DataAnnotation with "caption"

public enum ContactTypes
    {
        [Display(Name = "Società")]
        Company = 0,
        [Display(Name = "Persona")]
        Person = 1
    }

 

how can I retrieve this "caption" into DataTextField property? 

 

 

1 Answer, 1 is accepted

Sort by
0
Dimitar
Telerik team
answered on 07 May 2020, 12:53 PM

Hello Dario,

One possible approach of tackling this issue is to create a list out of the enum, by also retrieving the DisplayName custom attribute:

1) Sample controller implementation:

public IActionResult GetContactTypes() { var contactTypes = new List<object>(); var list = new List<object>();

foreach (var item in Enum.GetValues(typeof(ContactTypes))) { var displayAttribute = item .GetType() .GetMember(item.ToString()) .First() .GetCustomAttribute<DisplayAttribute>().Name; list.Add(new { Text = displayAttribute, Value = (int)item }); } return Json(list); }

2) Specify the DataTextField and DataValueField options according top the returned JSON data:

@(Html.Kendo().ComboBox()
    .Name("products")
    .DataTextField("Text")
    .DataValueField("Value")
    .DataSource(source =>
    {
            source.Read(read =>
            {
                read.Action("GetContactTypes", "Home");
            })
            .ServerFiltering(true);
    })
)

Regards,
Dimitar
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
Tags
ComboBox
Asked by
Dario
Top achievements
Rank 1
Veteran
Answers by
Dimitar
Telerik team
Share this question
or