How do you set value of dropdownlist grid column to field from model instead of a hardcoded default?

1 Answer 1628 Views
DropDownList Grid
SK
Top achievements
Rank 2
Iron
Iron
SK asked on 25 Feb 2022, 07:09 PM

I have a grid which lets you create a new row and default values are set. When you create a new row, an API call is made to retrieve the default values which populates the columns. However I would like to set the default value of one of those columns but it is a dropdownlist column (separate API call that gets the values for that column). 

To be more specific, I'm confused about is how to get the value "displayvalue" from the UVLJournalEntries model and set it as the default value for the dropdownlist. For example I have "default value" hardcoded here:

                    items.Add().Text("Journal Entries").Content(@<text>
                                @(Html.Kendo().Grid<ArusUI.Areas.UVL.Models.UVLJournalEntriesModel>()
                     .Name("JEGrid_#=PONum#_#=lineNum#") // template expression, to be evaluated in the master context
                      .Columns(columns =>
                      {
                          columns.Bound(p => p.distrPercent).Title("Distribution Percent").Width(16);
                          columns.Bound(p => p.amt).Title("Amount").Width(21); ;
                          columns.Bound(p => p.newCostCenter).Title("Cost Center")
                            .Width(18)
                            .ClientTemplate("\\#=newCostCenter.displayvalue\\#")
                            .Filterable(false);
                          columns.Bound(p => p.acctNum).Title("Account Nbr")
                            .Width(18);
                          columns.Bound(p => p.subAcctNum).Title("Sub Account Nbr")
                              .Width(17);
                          columns.Bound(p => p.refType).Title("Reference Type").Width(20);
                          columns.Bound(p => p.refNum).Title("Reference Nbr").Width(21);
                          columns.Bound(p => p.refSubNum).Title("Reference Sub Nbr").Width(25);
                          columns.Bound(p => p.project).Title("Project Nbr").Width(20);
                          columns.Bound(p => p.activityID).Title("Activity ID").Width(20);
                          columns.Bound(p => p.userDef).Title("User Defined").Width(25);
                      })
                              .ToolBar(toolbar =>
                              {
                                  toolbar.Create().HtmlAttributes(new { Id = "AddId_#=PONum#_#=lineNum#" });
                                  toolbar.Custom().Text("Undo").Name("Cancel").HtmlAttributes(new { Id = "UndoId_#=PONum#_#=lineNum#" });

                              })
                            .Editable(editable => editable.Mode(GridEditMode.InCell))
                            .Selectable(selectable => selectable
                                        .Mode(GridSelectionMode.Single))
                            .Events(ev => ev.Edit("onJEEdit"))
                            .DataSource(dataSource => dataSource
                                .Ajax()
                                .PageSize(10)
                            .Model(model =>
                            {
                                model.Id(field => field.id);
                                //model.Field(field => field.newCostCenter.displayvalue).Editable(true);
                                model.Field(field => field.newCostCenter).DefaultValue(new ArusUI.Areas.UVL.Models.CostCenterModel() { displayvalue = "default value" });
                            })
                            )
                            .Sortable()
                            .Pageable()
                            .Resizable(resize => resize.Columns(true))
                            .Width(2050)
                            .ToClientTemplate())
                    </text>

That part that I highlighted in orange kind of explains what I tried to do but I get the error "newCostCenter" is not defined.

This is the Edit event which populates the default values:

function onJEEdit(e) {
    var URL = '/UVL/GetJournalEntries/'
    var arrValues = e.sender._cellId.split('_');
    var lineNbr = arrValues[2].substring(0, 4);
    var PONbr = arrValues[1];
    var POReleaseNbr;


    if (PONbr.length <= 8) {
        POReleaseNbr = "";
    } else {
        POReleaseNbr = PONbr.substring(0, 8);
    };

    var jeGrid = $(`#JEGrid_${PONbr}_${arrValues[2]}`).data("kendoGrid");
    var detailGridWrapper = jeGrid.wrapper;
    var parentRow = detailGridWrapper.closest("tr.k-detail-row").prev("tr");
    var parentGrid = parentRow.closest("[data-role=grid]").data("kendoGrid");
    var parentModel = parentGrid.dataItem(parentRow);
    var JEGridData = jeGrid.dataSource.data();
    var oldData = jeGrid.dataSource._pristineData;
    var newData = jeGrid.dataSource._data;

    var dataText = $("#Facility").data("kendoDropDownList").text();
    var facility = dataText.split('-');
    var _facilityCode = $.trim(facility[0]);
    var _facilityDesc = $.trim(facility[1]);

    $.ajax({
        type: 'GET',
        url: URL,
        data: { facility: _facilityCode, description: _facilityDesc, purchaseOrderNbr: PONbr, poReleaseNbr: POReleaseNbr, lineNbr: lineNbr },
        dataType: 'json',
        success: function (data) {
            test = data;
            if (data != "error" && data != undefined) {

                var distrPercent = data.journalEntries[0].distrPercent;
                costCenter = data.journalEntries[0].costCenter;
                account = data.journalEntries[0].acctNum;
                amt = data.journalEntries[0].amt;
                referenceType = data.journalEntries[0].refType;
                referenceNbr = data.journalEntries[0].refNum.toString();
                referenceSubNbr = data.journalEntries[0].refSubNum;
                if (data.journalEntries[0].projectNbr != null) { projectNbr = data.journalEntries[0].projectNbr; };
                if (data.journalEntries[0].activityId != null) { activityId = data.journalEntries[0].activityId; };              
                userDef = data.journalEntries[0].userDef;

                if (e.model.isNew() && !e.model.dirty) {

                    newData[0].set("distrPercent", distrPercent);
                    newData[0].set("amt", amt);
                    newData[0].set("refType", referenceType);
                    newData[0].set("refNum", referenceNbr);
                    newData[0].set("refSubNum", referenceSubNbr);
                    newData[0].set("project", projectNbr);
                    newData[0].set("activityID", activityId);
                    newData[0].set("userDef", userDef);

                } else {
                    //not complete

                }


            }
            else {
                Swal.fire(
                    'Something went wrong!',
                    'Please Try again',
                    'error'
                );
            }
        }

    });

}

 

Here are the controller methods for getting default values (GetJournalEntries) and getting the values for the dropdownlist column (GetCostCenter):

        public async Task<JsonResult> GetJournalEntries(string facility, string description, string purchaseOrderNbr, string poReleaseNbr, int lineNbr)
        {
            string baseUrl = string.Empty;
            HttpClientHandler clientHandler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
            };
            using var client = new HttpClient(clientHandler, true);
            int line = lineNbr;
            string lineNbrStr = UVLFunctions.FmtLineNbr(line);

            try
            {
                if (!String.IsNullOrEmpty(facility) && purchaseOrderNbr != null)
                {

                    baseUrl = _iconfiguration.GetValue<string>("API:UVL") + "/Jes/?facility="
                        + facility + "&description=" + description + "&purchaseOrderNbr=" + purchaseOrderNbr + "&poReleaseNbr=" + poReleaseNbr + "&lineNbr=" + lineNbrStr;

                    var response = await client.GetStringAsync(baseUrl);

                    JEGridModel allJEs = JsonConvert.DeserializeObject<JEGridModel>(response);

                    var id = 0;
                    foreach (var item in allJEs.journalEntries)
                    {
                        item.id = id;
                        id++;
                    };

                    allJEs.journalEntries.ForEach(c => c.newCostCenter = new CostCenterModel() { displayvalue = c.costCenter });

                    return Json(allJEs);
                }
                else
                {
                    return Json("");
                }
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }



        public async Task<JsonResult> GetCostCenter(string facilityCode, string facilityDesc)
        {
            try
            {
                string baseUrl = _iconfiguration.GetValue<string>("API:UVL") + "/CostCenters/?facility=" + facilityCode + "&description=" + facilityDesc;

                HttpClientHandler clientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
                };

                var json = await new HttpClient(clientHandler).GetStringAsync(baseUrl);

                CostCenterListModel costCenter = JsonConvert.DeserializeObject<CostCenterListModel>(json);
                //costCenter.uvlCostCenter.Sort((v1, v2) => v1.displayvalue.CompareTo(v2.displayvalue));
                return Json(costCenter.uvlDatalist);
            }
            catch (System.Exception e)
            {
                throw e;
            }

        }

 

EditorTemplate for dropdownlist column:

@model ArusUI.Areas.UVL.Models.CostCenterModel
@using Kendo.Mvc.UI

@(Html.Kendo().DropDownListFor(model=>model)
        .DataValueField("displayvalue")
        .DataTextField("displayvalue")
        .OptionLabel("--Select--")
        .HtmlAttributes(new { style = "font-size:inherit;width:100%;height:1.3rem;align-items: center" })
.DataSource(source =>
{
    source.Read(read =>
    {
        read.Action("GetCostCenter", "UVL").Data("GetFacilityCode");
    }).ServerFiltering(false);
})
)

 

Model for journal entry grid and model for dropdownlist:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace ArusUI.Areas.UVL.Models
{
    public class JEGridModel
    {
        public List<UVLJournalEntriesModel> journalEntries { get; set; }
    }
    public class UVLJournalEntriesModel 
    {
        public int id { get; set; }
        [Range(0, 100)]
        public string distrPercent { get; set; }
        public int amt { get; set; }
        [UIHint("UVL/CostCenter")]
        public CostCenterModel newCostCenter { get; set; }
        public string costCenter { get; set; }
        [UIHint("UVL/AccountNumber")]
        public AccountNumberModel newAccountNumber { get; set; }
        public string acctNum { get; set; }
        public string subAcctNum { get; set; }
        public string refType { get; set; }
        public string refNum { get; set; }
        public string refSubNum { get; set; }
        public string project { get; set; }
        public string activityID { get; set; }
        public string userDef { get; set; }

    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ArusUI.Areas.UVL.Models
{
    public class CostCenterListModel
    {
        public List<CostCenterModel> uvlDatalist { get; set; }
    }
    public class CostCenterModel
    {
        public string displayvalue { get; set; }

    }
}
I tried following this demo (Editing custom editor in ASP.NET Core Grid Component Demo | Telerik UI for ASP.NET Core) initially but I am very new so I couldn't understand exactly what I needed to change in my own code. If you have suggestions on what I should do, please let me know (and if possible be very descriptive so I can understand). Thank you for your time. 

1 Answer, 1 is accepted

Sort by
1
Accepted
Stoyan
Telerik team
answered on 02 Mar 2022, 04:56 PM

Hi SK,


The Custom editing Demo of the Grid showcases one approach to set a default value for the Grid by using a weakly typed ViewData["categories] and ViewData["defaultCategory"] instances of the Model bound to the Grid. These are populated with data by the PopulateCategory method used in the Editing_CustomController.cs.

To extend this functionality you can set a default value for the property of the CostCenterModel passed to the DataValueField configuration property of the DropDownList:

   public class CostCenterModel
    {
        public int CostCenterID { get; set; } = 1;
        public string displayvalue { get; set; };
    }
@(Html.Kendo().DropDownListFor(model=>model)
        .DataValueField("CostCenterID")
        .DataTextField("displayvalue")
        .OptionLabel("--Select--")
}

This way the default value of the DropDownList will be populated by the model and when a row is edited the value of the newCostCenter column will be preselected in the DropDownList as well. This is the reason this approach is favorable.

Alternatively, if you'd like to evaluate the default value dynamically you can either set this up in the Controller

@{
     var defaultCenter = ViewData["defaultCenter"] as CostCenterModel;
} 
@(Html.Kendo().DropDownListFor(model=>model)
        .DataValueField("displayvalue")
        .DataTextField("displayvalue")
        .OptionLabel("--Select--")
        .Value(defaultCenter.displayvalue)
        ...
}

or perform an jQuery.ajax to request the data and then use the value method of the DropDownList to set it.

$(document).ready(function(){ $.ajax({ url: "MyCustomController", success: function(data) { var dropdown = $("#newCostCenter").data("kendoDropDownList"); dropdown.value(data) } }); })

The approach of binding the Grid's model field to a default value remains the same.

Please note that in all of the approaches above you need to set a value that is already part of the DropDownList's data.


I hope the information above is useful in the scenario at hand.

Regards,
Stoyan
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
DropDownList Grid
Asked by
SK
Top achievements
Rank 2
Iron
Iron
Answers by
Stoyan
Telerik team
Share this question
or