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

Using enum in popup edit, when modifying grid view

4 Answers 558 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Erik
Top achievements
Rank 1
Veteran
Erik asked on 13 Apr 2021, 01:50 PM

Hi Progress,

Im currently trying to develop an grid view through your beautifully developed Kendo grid. 

The grid is displayed properly with the grid displaying the enum value as i wish. However i have stumbled upon a problem when using the GridEditMode.PopUp.

When pressing Add new Feature the option i can choose is the Enums key, not the value. My wish is to make an dropdown list of these enums for available features an user can choose from. And not the Key. 

I will supply my code here. 

@(Html.Kendo().Grid<X.Administration.UI.Models.FeaturesGridViewModel>
    ()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Id).Hidden();
        columns.Bound(p => p.Tag);
    })
    .ToolBar(toolbar => toolbar.Create().Text("Add new feature"))
    .Editable(editable => editable.Mode(GridEditMode.PopUp))
    .Pageable()
    .Sortable()
    .Scrollable()
    .HtmlAttributes(new { style = "height:430px;" })
    .DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(10)
    .Events(events => events.Error("error_handler"))
    .Model(model => model.Id(p => p.Id))
    .Read(read => read.Action("GetFeaturesByCarId", "Grid", new {id = @Model.Id}))
    .Update(update => update.Action("AddFeatureByVehicleId", "Feature", new { id = @Model.Id }))
    )
    )

Iv'e attached files displaying how it looks now, and what i wish for. My wish is to have an Html.Kendo().DropDownList() in my popup, when adding an entry. However i am not able to create one in my GridEditMode.PopUp. 

The result im looking for is similar to that of an Kendo drop down list. However iv'e been unable to locate an example in in the forums for ASP.NET CORE, using an dropdown of all available enums.

 

 

 

 

4 Answers, 1 is accepted

Sort by
0
Mihaela
Telerik team
answered on 16 Apr 2021, 01:33 PM

Hello Erik,

Thank you for sharing a code snippet and screenshots.

You could display the Enum data field in the Popup editor as follows:

  • Create a View in the ~Views\Shared\EditorTemplates folder and initialize a dropdown widget.
@using ProjectName.Models

@(Html.Kendo().DropDownListFor(m => m)
 .BindTo(Extensions.EnumToSelectList(typeof (Tag)))
)
  • It should be bound to 'IEnumerableCollection' (it is highlighted in yellow in the code snippet above). In your case, you could define a static method, which would accept an Enum data filed (i.e. "Tag") and would return its key-value pairs as a List. For example:
public static class Extensions
{
      public static List<SelectListItem> EnumToSelectList(Type enumType)
      {
            return Enum
              .GetValues(enumType)
              .Cast<int>()
              .Select(i => new SelectListItem
              {
                  Value = i.ToString(),
                  Text = Enum.GetName(enumType, i),
              }
              )
              .ToList();
      }
}

Following this example, the method ''EnumToSelectList" will loop over the Enum items, set to each one 'value' and 'text' properties, and return them as a List.

  • Decorate the model property with the UIHint attribute and the grid will invoke the editor. The name of the specified template should match with the name of the View, created in the ~Views\Shared\EditorTemplates folder (i.e "TagMenu").
public enum Tag { Value1, Value2, Value3 }

public class TagModel
{
    [UIHint("TagMenu")]
    public Tag Tag_Property { get; set; }
}
  • The grid's configuration remains the same.

Attached you can find a sample project with this example. Would you please give a try to this approach and let me know if it is applicable to your case?

In addition, you could review the demo below, which demonstrates how to add a dropdown menu as a custom column editor:

https://demos.telerik.com/aspnet-core/grid/editing-custom

I hope you find this helpful.

 

Regards, Mihaela Lukanova Progress Telerik

Тhe web is about to get a bit better! 

The Progress Hack-For-Good Challenge has started. Learn how to enter and make the web a worthier place: https://progress-worthyweb.devpost.com.

0
Erik
Top achievements
Rank 1
Veteran
answered on 19 Apr 2021, 06:51 AM

Hi Mihaela,

Thank you for an detailed and clear explanation. It was exceptional help and i am very thankful for your time spent providing an example, as it has helped my very much in my implementation of an dropdown inside my popup editor. I have taken your provided implementation in consideration when developing my grid.

The snippets i have provided is the code i used, and the picture is the result. 

Just like your example i created an static method that returns an SelectListItem, and an UI hint tag on the tag property. I have also created an "FeaturesEditor", which uses the SelectListItems, and displays them in an drop down. Finally the grid that i wanted to use the dropdown with uses the template inside the grid through, ".Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("FeaturesEditor"))" as displayed in my provided snippets. 

Big thanks to you and for the exceptional help you get from Progress. Cheers. 

Regards Erik

FeaturesEditor.cshtml
public async Task<JsonResult> GetFeaturesByCarId([DataSourceRequest] DataSourceRequest request, int id)
      {
          var vehicle = await _vehicleService.GetVehicleById(id);
 
          var vehicleFeatures = vehicle.VehicleFeatures.Select(x => x.Feature);
 
          var vehicleFeaturesResource = _mapper.Map<IEnumerable<Feature>, IEnumerable<FeaturesGridViewModel>>(vehicleFeatures);
 
          return Json(vehicleFeaturesResource.ToDataSourceResult(request));
      }
Home.cshtml
@model X.Administration.UI.Models.VehicleViewModel
<h3>Car Features</h3>
@(Html.Kendo().Grid<X.Administration.UI.Models.FeaturesGridViewModel>
    ()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(x => x.Id).Hidden();
        columns.Bound(x => x.Tag);
    })
    .ToolBar(toolbar => toolbar.Create().Text("Add new feature"))
    .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("FeaturesEditor"))
    .Pageable()
    .Sortable()
    .Scrollable()
    .HtmlAttributes(new { style = "height:430px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .ServerOperation(false)
        .PageSize(10)
        .Events(events => events.Error("error_handler"))
        .Model(model =>
        {
            model.Field(p => p.Id);
            model.Field(p => p.Tag);
        })
        .Read(read => read.Action("GetFeaturesByCarId", "Grid", new {id = @Model.Id}))
        .Create(update => update.Action("AddFeatureByVehicleId", "Feature", new { vehicleId = @Model.Id }))))
FeaturesTagHelper.cs
public static List<SelectListItem> EnumToSelectList(Type enumType)
     {
         return Enum
           .GetValues(enumType)
           .Cast<int>()
           .Select(i => new SelectListItem
           {
               Value = i.ToString(),
               Text = Enum.GetName(enumType, i),
           }
           )
           .ToList();
     }
FeaturesGridViewModel.cs
public class FeaturesGridViewModel
    {
        public int Id { get; set; }
        [UIHint("TagMenu")]
        public FeaturesTag Tag { get; set; }
    }
FeaturesEditor.cshtml
@model X.Administration.UI.Models.FeaturesGridViewModel
@using X.Administration.UI.Models;
 
<div class="k-edit-form-container">
    <br />
    <div class="k-edit-field">
        @(Html.Kendo().DropDownListFor(m => m.Tag)
 .BindTo(FeaturesTagHelper.EnumToSelectList(typeof (X.Core.Enums.FeaturesTag)))
)
    </div>
</div>
0
Erik
Top achievements
Rank 1
Veteran
answered on 19 Apr 2021, 06:54 AM

Hi again,

need to address the wrongful naming of FeaturesEditor.cshtml. It is GridController.cs that is the rightful name and not FeaturesEditor.cshtml.  

 

Cheers Erik

0
Mihaela
Telerik team
answered on 19 Apr 2021, 02:20 PM

Hello Erik,

Thank you for sharing your code with the community! I am glad that the shared demo project has proven helpful.

In case any questions arise, feel free to contact me back.

 

Regards, Mihaela Lukanova Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
Grid
Asked by
Erik
Top achievements
Rank 1
Veteran
Answers by
Mihaela
Telerik team
Erik
Top achievements
Rank 1
Veteran
Share this question
or