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

How to display enumerated values?

1 Answer 1511 Views
TreeList
This is a migrated thread and some comments may be shown as answers.
wb
Top achievements
Rank 1
wb asked on 19 Feb 2019, 12:33 PM

I want to display an enumeration variables in TreeList Column , for example :

public enum TrafficType
    {
        [Display(Name = "Car-1")]
        Car = 1,
        [Display(Name = "Train-2")]
        Train = 2,
        [Display(Name = "Airplane-3")]
        Airplane = 4
    }

If Telerik Grid, I can write code as follows:

columns.Bound(p => p.Category).ClientTemplate("#=Category.CategoryName#").Width(180);

But for Treelist, how can I do?


1 Answer, 1 is accepted

Sort by
0
Tsvetomir
Telerik team
answered on 21 Feb 2019, 02:43 PM
Hello,

The serialization of an object and an Enum is different in ASP.NET Core. The serialization of an Enum return only its numeric value. So, it would not be possible to access the Name of the Display attribute directly. What you can do is to pass the Enum collection to JavaScript and using Templates to match the values. 

1. Initialize the Enum and set the values from 0:

public enum TrafficType
{
    [Display(Name = "Car-1")]
    Car = 0,
    [Display(Name = "Train-2")]
    Train = 1,
    [Display(Name = "Airplane-3")]
    Airplane = 2
}

2. Add the list of the Enum's names to the ViewData:

public IActionResult Index()
{
    ViewData["enumList"] = Enum.GetNames(typeof(TrafficType));

3. Assign a Template to the column:

columns.Add().Field(e => e.TrafficType).Template("#: displayEnum(data)#");

4. Retrieve the collection and set the names:

<script>
    var collection = @Html.Raw(Json.Serialize(ViewData["enumList"]));
 
    function displayEnum(dataItem) {
        return collection[dataItem.TrafficType];
    }
</script>

Another approach would be to send the value names as a string directly. This approach would not be suitable if the numeric values of the Enum have to be used. More information can be obtained in the following StackOverflow article:

https://stackoverflow.com/questions/3464498/pass-c-sharp-asp-net-array-to-javascript-array


Kind regards,
Tsvetomir
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
TreeList
Asked by
wb
Top achievements
Rank 1
Answers by
Tsvetomir
Telerik team
Share this question
or