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

Displaying enum values in grid using custom binding

18 Answers 654 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Nick Pepper
Top achievements
Rank 1
Nick Pepper asked on 05 May 2010, 02:48 PM
Hi there

I was wondering if there was a way to display an Enum's name value in the Telerik mvc grid. I'm using custom binding and my grid currently displays the integer values of the enum and i want it to display the corresponding name values to the user whilst still allowing them to use the enum filtering options. I'm using VB.NET and the MVC 1 telerik extensions version 2010.1.309. Please find a code snippet below. The column colCurrentStatus uses the ContractStatus enum. Please can you let me know if and then how this can be done.

Many thanks in advance

Nick

<%                                                           
            Dim grid As Telerik.Web.Mvc.UI.Grid(Of Contracts.ContractsSummaryViewModel) = Html.Telerik.Grid(Of Contracts.ContractsSummaryViewModel) _ 
            .Name("ContractGrid") _ 
            .Sortable() _ 
            .Pageable(Function(p) p.Total(CInt(ViewData("Total")))) _ 
            .Filterable() _ 
            .Selectable() _ 
            .EnableCustomBinding(True) _ 
            .ClientEvents(Function(events) events.OnRowSelected("onRowSelected")) _ 
            .DataBinding(Function(d) d.Ajax().Select("GetContracts", "Contracts")) 
            grid.Paging.PageSize = 20 
            Dim colContractId As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.ID) 
            Dim colContractName As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.ContractName) 
            Dim colPORef As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.PORef) 
            Dim colClient As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.Client) 
            Dim colCurrentStatus As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, Contracts.ContractStatus)(grid, Function(c) c.ContractStatus) 
            Dim colStartDate As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.StartDate) 
            Dim colEndDate As New Telerik.Web.Mvc.UI.GridBoundColumn(Of Contracts.ContractsSummaryViewModel, String)(grid, Function(c) c.EndDate) 
            colCurrentStatus.Title = "Current Status" 
            colContractId.Sortable = False 
            colContractId.Filterable = False 
            colCurrentStatus.Filterable = True 
            colStartDate.Sortable = False 
            colEndDate.Sortable = False 
            grid.Columns.Add(colContractId) 
            grid.Columns.Add(colContractName) 
            grid.Columns.Add(colPORef) 
            grid.Columns.Add(colClient) 
          grid.Columns.Add(colCurrentStatus) 
            grid.Columns.Add(colStartDate) 
            grid.Columns.Add(colEndDate) 
            grid.Render() 
        %> 

18 Answers, 1 is accepted

Sort by
0
Accepted
Atanas Korchev
Telerik team
answered on 05 May 2010, 04:33 PM
Hello Nick Pepper,

There are two ways to do this:
  1. Create another object which will have the same properties as ContractsSummaryViewModel except the enum. Create a property of string type and same name as the enum property. Map the enum value to that property and return the new object when doing ajax binding. Continue to use ContractsSummaryViewModel when defining the grid in order to trick the grid that there is an enum.
  2. Use a client template for the enum column in order to display it as string. You will need a helper javascript array containing all enum values. Here is a code snippet:

    <script type="text/javascript">
     var enumValues = ["FirstValue", "SecondValue"];
    </script>
    ....
    column.ClientTemplate = "<#= enumValues[EnumProperty] #>"

Regards,
Atanas Korchev
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
0
Nick Pepper
Top achievements
Rank 1
answered on 14 May 2010, 10:25 AM
I tried the first solution which seems to work fine.

Many thanks

Nick
0
David Guthu
Top achievements
Rank 1
answered on 24 Jul 2010, 12:15 AM
Has functionality here changed at all with the release of Q2 beta?
0
Georgi Krustev
Telerik team
answered on 26 Jul 2010, 08:51 AM
Hello David,

I do not believe that there are any major changes in this functionality.

Greetings,
Georgi Krustev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Alex
Top achievements
Rank 1
answered on 27 Jun 2011, 05:20 PM
Hi,

I have a similar issue. And your 2nd suggestion works fine. However, when I add the inline edit functionality, the enum field does not show as dropdownlist. It shows as an edit text box. Any suggestion?

Thank you,
Alex
0
Mike
Top achievements
Rank 1
answered on 20 Jul 2011, 07:18 PM
I am surprised that I cannot annotate my enum with a UIHint("SomeTemplateName") and drop a DisplayTemplate in the Shared Views that renders the Enum for me in the way I want, especially since it appears that I can do that for an Editor Template.

If I do that the display template appears to be ignored, and the default rendering is the enum's integer value.
0
Ciprian
Top achievements
Rank 1
answered on 17 Aug 2011, 02:19 PM
Hello Atanas,
can you please submit a short example for the first solution?

Thanks,
Julian
0
Atanas Korchev
Telerik team
answered on 17 Aug 2011, 02:49 PM
Hello Iulian,

Here is a simple example:

<script type="text/javascript">
 var enumValues = ["FirstValue", "SecondValue"];
</script>

<%: Html.Telerik().Grid<MyModel>()
                .Columns(columns =>
                {
                      columns.Bound(o => o.EnumProperty).ClientTemplate("<#= enumValues[EnumProperty] #>");
                })
                .DataBinding(dataBinding => dataBinding.Ajax().Select("Select", "Home"))
%> 

Regards,
Atanas Korchev
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items

0
Ciprian
Top achievements
Rank 1
answered on 17 Aug 2011, 06:58 PM
Thank you,

this example is for the second solution, right?
What about the first solution, how to map the enum value to the property?

Regards,
Iulian
0
Alex
Top achievements
Rank 1
answered on 17 Aug 2011, 07:40 PM
Hi Lulian,

Try this...

 

Your object data
public
EnumType YourEnumType { get; set; }

public string YourEnumTypeName

 {

get { return Enum.GetName(typeof(EnumType ), YourEnumType ); }

}

Your mvc codes:
columns.Bound(c => c.YourEnumTypeName).Title("Your Column Title")

let me know if this works for you.
Alex

 

0
Ciprian
Top achievements
Rank 1
answered on 18 Aug 2011, 08:44 AM
Thanks Alex,

it shows ok but the filtering doesn't work.
Is there a workaround for that too?

Regards,
Iulian
0
Jatin
Top achievements
Rank 1
answered on 18 Aug 2011, 03:58 PM
Alex,
     I have the same problem as lulian. Basically, I wan't the Enum descriptions to show up in the grid column and the column should be filterable as it is for normal enum. That is, the filter should display enum descriptions to select from and when selected the filter should be applied based on that descrption of the enum. Any trick that can help me?

Currently with your solution, I can display the enum descriptions but the filtering does not work the way it works for any enum column.

regards,
Nirvan
0
Ciprian
Top achievements
Rank 1
answered on 22 Aug 2011, 09:44 AM
Hello Atanas,

is there a way to use your ClientTemplate solution with AutoGenerated colums?

Thanks,
Iulian
0
Atanas Korchev
Telerik team
answered on 22 Aug 2011, 10:09 AM
Hello Iulian,

 Yes, my solution will work with auto generated columns. Find attached a sample project.

Best wishes,
Atanas Korchev
the Telerik team

Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

0
Tim
Top achievements
Rank 1
answered on 11 Oct 2011, 08:34 PM
Hi Guys,

I am using enums in the telerik grid and have implemented it client side using the 2nd solution above. It is displaying properly however Filtering is not working for the enum column only. It works for all my other columns including other client template columns. I get a 

Microsoft JScript runtime error: Object doesn't support property or method 'toLowerCase' that occurs in the telerik.common.min.js  

in the line 

e=function(aE){return aE.toLowerCase()}

Below is my code. Where Deliverable is come object with a property of type enum CompletionStatus containing two statuses "Active" and "Complete". Any help would be appreciated as this is the main field that gets filtered.

<script type="text/javascript">
function(var CompletionStatus)
{
    var enumValues = ["Active", "Complete"];    
}
</script> 
 
<h2>MyDeliverables</h2>
<div class="Main-Grid">
 
@( Html.Telerik().Grid <DeliverableModel.Deliverable>()
        .Name("Grid")
        .Columns(columns =>
        {           

            columns.Bound(o => o.CompletionStatus).ClientTemplate("<#= enumValues[CompletionStatus] #>").Width(15).Title("Status");
            columns.Command(commands =>
            {  
                              
                commands.Delete();
            }).Width(100);
        })
        .DataKeys(keys => keys.Add(o=> o.Id))
        .DataBinding(dataBinding =>
        {
            dataBinding.Ajax().OperationMode(GridOperationMode.Client)
                .Select("_MyDeliverablesGrid""Deliverables")
                .Delete("_MyDeliverablesDelete""Deliverables");
            //dataBinding.Server().Select("MyDeliverablesIndex", "Deliverables");
            
        })
        .Sortable()
        .Filterable()
        .Pageable(p=>p.PageSize(20))  
        .Resizable(r=>r.Columns(true))     
        .NoRecordsTemplate("You have no deliverables at this time.")    
       
)
0
Rosen
Telerik team
answered on 12 Oct 2011, 07:25 AM
Hi Tim,

Indeed, we are aware of this issue when client operation mode is enabled. The fix will be available with next official release and in the next internal build.

Regards,
Rosen
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
0
Ankur
Top achievements
Rank 1
answered on 19 Nov 2011, 02:58 AM
Hi there,

I'm trying to extend the sample code provided here to allow dropdown editing in the grid of the enum as well; but I don't seem to be succeeding.

My view is defined like so:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Import Namespace="Daff.Lae.Web.Common.Models"  %>
 
<p>* denotes mandatory fields</p>
<script type="text/javascript">
    function onConsignmentRowEdit(e) {
        $(e.form).find("#ddlForeignCountry").data("tDropDownList").select(function (dataItem) {
            return dataItem.Text == e.dataItem["ForeignCountry"];
        });
    }
</script>
 
<div class="formGroup">
<%
    // get the noiId out of the ViewBag
    int noiId = ViewBag.NoiId ?? 0;
 
    Html.Telerik().Grid<ConsignmentViewModel>()
        .Name("grdConsignmentDetails")
        .ToolBar(command => command.Insert())
        .DataKeys(keys => keys.Add(consignment => consignment.ConsignmentId))
        .Localizable("en-AU")
        .DataBinding
        (
            x => x.Ajax()
                .Select("GetAll", "Consignment" , new RouteValueDictionary { {"noiId", noiId} })
                .Insert("Add", "Consignment")
                .Update("Update", "Consignment")
                .Delete("Remove", "Consignment")
        )               
        .Columns
        (
            c =>
                {
                    c.Command
                        (
                            command =>
                            {
                                command.Edit().ButtonType(GridButtonType.Text);
                                command.Delete().ButtonType(GridButtonType.Text);
                            }
                        ).Width(100);
                    c.Bound(m => m.Sex).EditorTemplateName("Sex").ClientTemplate("<#= Sex != null ? Sex.Name : '' #>").Width(200);
                    c.Bound(m => m.Age).EditorTemplateName("PositiveInteger").Width(200);
                    c.Bound(m => m.ArrivalDate).EditorTemplateName("Date").ClientTemplate("<#= $.telerik.formatString('{0:dd/MM/yyyy}', ArrivalDate) #>").Width(200);
                    c.Bound(m => m.DepartureDate).EditorTemplateName("Date").ClientTemplate("<#= $.telerik.formatString('{0:dd/MM/yyyy}', DepartureDate) #>").Width(200);
                    c.Bound(m => m.DestinationCountry).ClientTemplate("<#= countryNames[DestinationCountry] #>").Width(200);
                    c.Command
                        (
                            command =>
                            {
                                command.Edit().ButtonType(GridButtonType.Text);
                                command.Delete().ButtonType(GridButtonType.Text);
                            }
                        ).Width(100);
                }
        )
        .ClientEvents(events => events.OnEdit("onConsignmentRowEdit"))
        .Pageable(p =>
        {
            p.Enabled(true);
            p.PageSize(5);
        })
        .Scrollable(c => c.Height("auto"))
        .Render();
%>
</div>

I have an editor template for ForeignCountry:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Daff.Lae.Common.Types.ForeignCountry>" %>
<%@ Import Namespace="Daff.Lae.Common.Extensions" %>
<%@ Import Namespace="Daff.Lae.Common.Types" %>
 
<%: Html.Telerik().DropDownList().Name("ddlForeignCountry").BindTo(typeof(ForeignCountry).AsSelectList()) %>

And my ViewModel is pasted below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Daff.Lae.Common.Types;
 
 
namespace Daff.Lae.Web.Common.Models
{
    //[Bind(Exclude = "Species, Class, Commodity, Sex, SelectedPremises, DestinationCountry")]
    public class ConsignmentViewModel : IEnumerableViewModel
    {
        public int ConsignmentId { get; set; }
 
        public int NoiId { get; set; }
 
        [Required]
        [DisplayName("Quantity *")]
        public int Quantity { get; set; }
 
        [DisplayName("Species *")]
        public LivestockSpecies Species { get; set; }
 
        [DisplayName("Class *")]
        public LivestockClass Class { get; set; }
 
        [DisplayName("Commodity *")]
        public CommodityLivestock Commodity { get; set; }
 
        [DisplayName("Breed *")]
        public string Breed { get; set; }
 
        [DisplayName("Sex *")]
        public Sex Sex { get; set; }
 
        [Required]
        [DisplayName("Age *")]
        public int Age { get; set; }
 
        [DisplayName("Premises Name")]
        public PremisesViewModel SelectedPremises { get; set; }
 
        [Required]
        public int PremisesId { get; set; }
 
        [DisplayName("Country of Destination")]
        [UIHint("ForeignCountry"), Required]
        public ForeignCountry DestinationCountry { get; set; }
 
        [Required]
        [DisplayName("Expected Arrival Date (to premises) *")]
        public DateTime ArrivalDate { get; set; }
 
        [Required]
        [DisplayName("Expected Departure Date (from premises) *")]
        public DateTime DepartureDate { get; set; }
 
        [Required]
        [DisplayName("Import Permit Required?")]
        public bool ImportPermitRequired { get; set; }
 
        //Following are applicable only to NOI by Sea views
        [Required]
        [DisplayName("Port *")]
        public string Port { get; set; }
 
        [DisplayName("Proposed Arrival Date")]
        public DateTime ProposedArrivalDate { get; set; }
    }
 
}

Could you please help?
0
Rosen
Telerik team
answered on 21 Nov 2011, 09:19 AM
Hi Ankur,

Could you please provide a bit more information about what is the exact issue you are facing? Also a small sample which demonstrate it will be appreciated.

All the best,
Rosen
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
Tags
Grid
Asked by
Nick Pepper
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Nick Pepper
Top achievements
Rank 1
David Guthu
Top achievements
Rank 1
Georgi Krustev
Telerik team
Alex
Top achievements
Rank 1
Mike
Top achievements
Rank 1
Ciprian
Top achievements
Rank 1
Jatin
Top achievements
Rank 1
Tim
Top achievements
Rank 1
Rosen
Telerik team
Ankur
Top achievements
Rank 1
Share this question
or