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
There are two ways to do this:
- 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.
- 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.
Many thanks
Nick
I do not believe that there are any major changes in this functionality.
Greetings,
Georgi Krustev
the Telerik team
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
If I do that the display template appears to be ignored, and the default rendering is the enum's integer value.
can you please submit a short example for the first solution?
Thanks,
Julian
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"))
%>
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
this example is for the second solution, right?
What about the first solution, how to map the enum value to the property?
Regards,
Iulian
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
it shows ok but the filtering doesn't work.
Is there a workaround for that too?
Regards,
Iulian
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
is there a way to use your ClientTemplate solution with AutoGenerated colums?
Thanks,
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 >>
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.") )
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
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?
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