How to add dropdown inside grid with filter and group

Hi,

In the codes I sent in the attachment, I added dropdown for dialog edit in the grid (CustomerID field). But how can I search and group dropdown values when I select dropdown. These are available in the documentation as dropdown features, but I couldn't see how to do it in the grid dialog.


  <e-grid-column field="CustomerID" headerText="CustomerID" foreignKeyField="CustomerID" foreignKeyValue="OptionText" dataSource="@Model.DropDatasource" width="150"></e-grid-column>


Br,


Attachment: Razorpages_3f57a8e6.rar

14 Replies 1 reply marked as answer

JT John Taylor January 22, 2022 09:53 AM UTC

I saw another method on the forum. Adding dropdown to GridColumn with edit property. This way I can do dropdown filtering and grouping. However, there is an error. There are Text and Value fields in dropdowns. Text is the customername, value is the customerId field. In the attached image1, the relevant customer is selected, but then the customerid, not the customername, is displayed on the grid as in image2. How can I solve this? I have attached the sample codes. (Please don't tell me to set customername to dropdown value. CustomerId is unique and I need it in controller classes.)


Br,




Attachment: datagridWithDropdown_6bcc6b9.rar


RS Rajapandiyan Settu Syncfusion Team January 24, 2022 12:26 PM UTC

Hi John, 
 
Thanks for contacting Syncfusion support. 

Query #1: how can I search and group dropdown values when I select dropdown. 

You can achieve your requirement by using cellEditTemplate feature of Grid. In which you can customize the edit component as you want. 


Query #2: the relevant customer is selected, but then the customerid, not the customername, is displayed on the grid as in image2. How can I solve this? 

In your code example, the dataSource is not provided on foreignKey column. This is the cause of reported behavior. We suggest to bind dataSource on that column to resolve this. 

Find the below code example and sample for your reference. 


<e-grid-column field="EmployeeID" headerText="EmployeeID" foreignKeyField="EmployeeID" foreignKeyValue="Name" dataSource="@Model.DropDatasource" width="150" edit="@(new {create="create", read="read", destroy="destroy", write="write"})"></e-grid-column> 
 
<script> 
 
    var ddlObject; 
    var data = @Json.Serialize(@Model.DropDatasource); 
    function create() { 
        //  create a input element 
        return document.createElement('input'); 
    } 
 
    function read(args) { 
        // return the value which will be saved in the grid 
        return ddlObject.value; 
    } 
 
    function destroy() { 
        // destroy the custom component. 
        ddlObject.destroy(); 
    } 
 
    function write(args) { 
        // create a dropdown control 
        ddlObject = new ej.dropdowns.DropDownList({ 
            //bind the data  
            dataSource: data, 
            allowFiltering: true, // enable filtering 
            //bind the current cell value to the Dropdown which will be displayed only when the dropdown dataSource contains that value 
            value: args.rowData[args.column.field], 
            //map the appropriate columns to fields property 
            fields: { text: 'Name', value: 'EmployeeID', groupBy: 'IsAdult' }, 
            //set the placeholder to DropDownList input 
            placeholder: "Find a customer" 
        }); 
        //render the component 
        ddlObject.appendTo(args.element); 
    } 
</script> 



Please get back to us if you need further assistance. 

Regards, 
Rajapandiyan S 



JT John Taylor January 24, 2022 03:37 PM UTC

Thanks. It works.



RS Rajapandiyan Settu Syncfusion Team January 25, 2022 06:20 AM UTC

Hi John, 
 
We are glad that you have achieved your requirement with the provided solution. 

Please get back to us if you need further assistance. 

Regards, 
Rajapandiyan S 



JT John Taylor June 26, 2023 11:39 PM UTC

Hi,

I want to use combobox with search in datagrid,  instead of dropdownlist. If user enter "A", it must be take first record  which contains "A". how can I do this? 


Thanks.



HK Harini Kannan Syncfusion Team June 27, 2023 02:27 PM UTC

Hi John,


We understand that you need to change the filtering from dropdownlist to comboBox for a field. We have achieved your requirement by rendering combo box in the write function and appended it to the input field. We have attached the code snippet for your reference.


 

 create: function (args) {

          var dd = document.createElement('input');

          dd.id = 'ShipCity';

          return dd;

        },

        write: function (args) {

          var comboBoxObject = new ej.dropdowns.ComboBox({

            //bind the data manager instance to dataSource property

            dataSource: window.hierarchyOrderdata,

            //bind the Query instance to query property

            //map the appropriate columns to fields property

            fields: { value: 'ShipCity' },

            //set the placeholder to ComboBox input

            placeholder: 'Find a City',

            //set the filterType to searching operation

            filterType: 'StartsWith',

            //sort the resulted items

            sortOrder: 'Ascending',

          });

          comboBoxObject.appendTo('#ShipCity');

        },


Please let us know if you need any further assistance.


Regards,

Harini K R



JT John Taylor July 6, 2023 12:14 AM UTC

Hi,

In the Write method, I added the combobox with the Viewbag datasource and it worked fine. But I want it to work with UrlAdaptor because the data size is too big and I want it to come as I type. However, when adding Datamanager as in the code below, the grid did not work. I get the error "Uncaught TypeError: this.adaptor.processQuery is not a function". What am I doing wrong?


@{

    var datas = new Syncfusion.EJ2.DataManager

            {

                Url = Url.Action("GetVendorInventoryItemsForVendorOrder", "VendorInventoryItem"),

                Adaptor = "UrlAdaptor"

            };

}

<div>

    <ejs-grid id="GridMaster" dataSource="@Model.VendorOrderLineItems" gridLines="Both" height="272" allowPaging="false"

              allowSorting="true" allowResizing="true" allowReordering="true" allowGrouping="false"

              allowFiltering="true" toolbar="@(new List<string>() { "Add", "Edit", "Delete" })"

              allowSelection="true" allowExcelExport="true" allowTextWrap="true" created="created">

        <e-data-manager json="@Model.VendorOrderLineItems.ToArray()" adaptor="RemoteSaveAdaptor" insertUrl="/VendorOrder/InsertVendorOrderLineItem"

                        updateUrl="/VendorOrder/UpdateVendorOrderLineItem" removeUrl="/VendorOrder/DeleteVendorOrderLineItem"></e-data-manager>

        <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog" showDeleteConfirmDialog="true" allowEditOnDblClick="false"></e-grid-editSettings>

        <e-grid-selectionsettings type="Single"></e-grid-selectionsettings>

        <e-grid-textwrapsettings wrapMode="Both"></e-grid-textwrapsettings>

        <e-grid-columns>

            <e-grid-column field="Id" headerText="Id" isPrimaryKey="true" isIdentity="true" width="100" visible=false allowEditing="false" showInColumnChooser="false"></e-grid-column>

            <e-grid-column field="OrderLineItemPieceId" visible="false" headerText="OrderLineItemPieceId" width="200"></e-grid-column>

            <e-grid-column field="ClientId" visible="false" headerText="ClientId" defaultValue="@Model.ClientId" width="200"></e-grid-column>

            <e-grid-column field="OrderLineItemPieceId" visible="false" headerText="OrderLineItemPieceId" width="200"></e-grid-column>

            <e-grid-column field="VendorInventoryItemProductVariantSKU" headerText="SKU" width="100" allowEditing="false"></e-grid-column>

            <e-grid-column field="InventoryItemCost" headerText="Vendor Cost" width="100" textAlign="Right" format="C2" width="100" allowEditing="false"></e-grid-column>

            <e-grid-column field="OrderName" headerText="Order" width="150" allowEditing="false"></e-grid-column>

            <e-grid-column field="Note" headerText="Note" width="150"></e-grid-column>

            <e-grid-column field="VendorInventoryItemId" headerText="VendorInventoryItem" width="120" foreignKeyField="VendorInventoryItemId" foreignKeyValue="SKU"

                           edit="@(new {create="create", read="read", destroy="destroy", write="write"})" dataSource = "@datas" >


            </e-grid-column>


        </e-grid-columns>

    </ejs-grid>

</div>



<script>

    var ddlElem;

    var ddlObject;

    //var data = @Json.Serialize(ViewBag.Products);


    function create() {

        // create a input element

        ddlElem = document.createElement('input');

        return ddlElem;

    }


    function read() {

        // return the value which will be saved in the grid

        return ddlObject.value;

    }


    function destroy() {

        // destroy the custom component.

        ddlObject.destroy();

    }



    function write() {


        // create a autoComplete control

        ddlObject = new ej.dropdowns.ComboBox({

            //bind the data manager instance to dataSource property

            dataSource: new ej.data.DataManager({ url: '/VendorInventoryItem/GetVendorInventoryItemsForVendorOrder', adaptor: 'UrlAdaptor', crossDomain: 'true' }),

            //query = "new ej.data.Query().take(20).where('VendorLocationId', 'equal', $('#vendorLocationId').val())",

            //map the appropriate columns to fields property

            fields: { groupBy: 'Vendor', value: 'VendorInventoryItemId', text: 'SKU' },

            ////bind the current cell value to the Dropdown which will be displayed only when the dropdown dataSource contains that value

            //value: args.rowData[args.column.field],


            //set the placeholder to DropDownList input

            placeholder: "Select SKU",

            allowCustom: false,

            allowFiltering: true,

            filterType: 'StartsWith',

        });

        //render the component

        ddlObject.appendTo(ddlElem);

    }




    function created(args) {

        var vendorOrderStatus = document.getElementById('vendorOrderStatus').value;

     ....

    }

</script>




    function confirmApprove() {

     ....

    }




</script>




JC Joseph Christ Nithin Issack Syncfusion Team July 18, 2023 10:58 PM UTC

Hi John,


   Based on your query, you want to render a ComboBox component in the edit template of a column in the EJ2 Grid. You also want to bind the data using url adaptor to the combo box and filter the list with startswith filter operator. We have achieved the same using the below approach where we have rendered a combobox in the editemplate of the ShipCountry column and bind the data with url adaptor.


Please refer the below code example:


 

[Index.cshtml]

 

<div>

    <ejs-grid id="Grid" height="500" showColumnChooser="true" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update", "ColumnChooser"})">

        <e-data-manager url="/Home/UrlDatasource" adaptor="UrlAdaptor"></e-data-manager>

        <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog"></e-grid-editSettings>

        <e-grid-columns>

            <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="120"></e-grid-column>

            <e-grid-column field="CustomerID" headerText="Customer Name" width="150"></e-grid-column>

            <e-grid-column field="EmployeeID" headerText="Employee ID" width="170"></e-grid-column>

            <e-grid-column field="ShipCountry" headerText="Ship Country" width="170" edit="@(new {create = "create", read = "read", destroy = "destroy", write = "write"})"></e-grid-column>

        </e-grid-columns>

    </ejs-grid>

</div>

 

 

<script>

    var comboBoxobj;

    var element;

 

    function create(args) {

        element = document.createElement('input');

        return element;

    }

 

    function write(args) {

        var data = new ej.data.DataManager({

            url: "/Home/ComboUrlDatasource",

            adaptor: new ej.data.UrlAdaptor,

            crossDomain: true

        });

        comboBoxobj = new ej.dropdowns.ComboBox({

            dataSource: data,

            value: args.rowData[args.column.field],

            fields: { text: 'ShipCountry', value: 'ShipCountry' },

            placeholder: 'Select a Country',

            allowCustom: false,

            allowFiltering: true,

            filterType: 'StartsWith',

        });

        comboBoxobj.appendTo(element);

    }

 

    function destroy() {

        comboBoxobj.destroy();

    }

 

    function read(args) {

        return comboBoxobj.value;

    }

 

</script>

 

[HomeController.cs]

 

 

        public IActionResult UrlDatasource([FromBody] DataManagerRequest dm)

        {

            IEnumerable DataSource =  new List<OrdersDetails>();

            int count = OrdersDetails.GetAllRecords().Cast<object>().Count();

                DataSource = OrdersDetails.GetAllRecords();

                DataOperations operation = new DataOperations();

                if (dm.Search != null && dm.Search.Count > 0)

                {

                    DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search

                }

                if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting

                {

                    DataSource = operation.PerformSorting(DataSource, dm.Sorted);

                }

                if (dm.Where != null && dm.Where.Count > 0) //Filtering

                {

                    DataSource = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);

                }

                if (dm.Skip != 0)

                {

                    DataSource = operation.PerformSkip(DataSource, dm.Skip);   //Paging

                }

                if (dm.Take != 0)

                {

                    DataSource = operation.PerformTake(DataSource, dm.Take);

                }

                return dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource);

        }

 

        public ActionResult ComboUrlDatasource([FromBody] Data dm)

        {

            var val = OrdersDetails.GetAllRecords();

            var Data = val.ToList();

            var count = val.Count();

            if (dm.where != null)

            {

                Data = (from cust in Data

                        where cust.ShipCountry.ToLower().StartsWith(dm.@where[0].value.ToString().ToLower())

                        select cust).ToList();

            }

            if (dm.take != 0)

                Data = Data.Take(dm.take).ToList();

            return Json(Data);

        }

 

 


Regards,

Joseph I.

If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.




JT John Taylor July 19, 2023 01:00 PM UTC

I tried it, but I have 3 more questions about it:


1- How can I send the information in the two fields on the screen as parameters to the UrlDatasource Action, which sends data for the ComboBox?


         <input type="text" id="vendorId" value="@Model.VendorId" hidden>

         <input type="text" id="clientId" value="@Model.ClientId" hidden>


2- Is it possible to return a field other than text and value fields from the Combobox? For example; I am searching for a product from combobox, product name is text, productId Value, productCost Cost. And can I also send this productCost information to Action while saving?


3- How can I reload the page with the grid after the add or edit operation in the grid. It didn't happen when I redirected from the Add/Edit actions.


Thanks for your help.



DR Deepak Ramakrishnan Syncfusion Team July 20, 2023 01:21 PM UTC

Hi John,


  Query 1: How can I send the information in the two fields on the screen as parameters to the UrlDatasource Action, which sends data for the ComboBox?


        You can send additional parameters to the server side using the `query.addParams` method.


         Please refer the below code example.


[Index.cshtml]

 

  function write(args) {

        var data = new ej.data.DataManager({

            url: "/Home/ComboUrlDatasource",

            adaptor: new ej.data.UrlAdaptor,

            crossDomain: true

        });

        comboBoxobj = new ej.dropdowns.ComboBox({

            dataSource: data,

            query: new ej.data.Query().addParams('CustomerID', args.rowData['CustomerID'].toString()).addParams('EmployeeID', args.rowData['EmployeeID']),

            value: args.rowData[args.column.field],

            fields: { text: 'ShipCountry', value: 'ShipCountry' },

            placeholder: 'Select a Country',

            allowCustom: false,

            allowFiltering: true,

            filterType: 'StartsWith',

            change:(args)=> {

                console.log(args.itemData);

            }

        });

        comboBoxobj.appendTo(element);

    }

 

[HomeController.cs]

 

public ActionResult ComboUrlDatasource([FromBody] Data dm)

        {

            var val = OrdersDetails.GetAllRecords();

            var Data = val.ToList();

            var count = val.Count();

            if (dm.where != null)

            {

                Data = (from cust in Data

                        where cust.ShipCountry.ToLower().StartsWith(dm.@where[0].value.ToString().ToLower())

                        select cust).ToList();

            }

            if (dm.take != 0)

                Data = Data.Take(dm.take).ToList();

            return Json(Data);

        }

 

public class Data

    {

        public int take { get; set; }

        public List<Wheres> where { get; set; }

 

        public string? CustomerID { get; set; }

 

        public int? EmployeeID { get; set; }

    }

 


Please refer the below screenshots:


Screenshot 1:


Screenshot 2:


Query 2: Is it possible to return a field other than text and value fields from the Combobox? For example; I am searching for a product from combobox, product name is text, productId Value, productCost Cost. And can I also send this productCost information to Action while saving.


  Yes, you can return values other than the field required for the comboBox from the server side. Please refer the below screenshots.


Screenshot 1:


  


Screenshot 2:



Query 3: How can I reload the page with the grid after the add or edit operation in the grid. It didn't happen when I redirected from the Add/Edit actions.


     Before proceeding with the solution, we would like you to share the below details so that we will be able to provide a better solution.


  • Please explain your requirement in detail.
  • Confirm your requirement is the added/edited values not updated in the row?
  • Explain the use case why you want to reload the entire page when adding/editing the row.


Regards,

Joseph I.



JT John Taylor July 20, 2023 10:12 PM UTC

 Hi,


Query 1: Ok. It works.


Query 2:  I can return values other than the field required for the comboBox from the server side. But how I get these values with javascript? Because fields property only has the following fields. During the add/edit process, I want to take a field other than text and value in the json data from the combox query and send it to the Action during the save process.

fields

FieldSettingsModel

The fields property maps the columns of the data table and binds the data to the component.

  • text - Maps the text column from data table for each list item.
  • value - Maps the value column from data table for each list item.
  • iconCss - Maps the icon class column from data table for each list item.
  • groupBy - Group the list items with it’s related items by mapping groupBy field.


Query 3:  

In the example you gave, the text and value are the same. both ShipCountry.

I want to do this:

I need to get Text= SKU, Value= Product.Id in return value from my own model to combobox. I also set my column in the Grid to "<e-grid-column field="Product.Id" ". In Add/Edit I have to show the value of Text= SKU from combobox, I have to send Value= Product.Id to Action. After the save, I have to show the Text= SKU in the Grid.


Br,


JC Joseph Christ Nithin Issack Syncfusion Team July 21, 2023 02:46 PM UTC

Hi John,



Query 1:


  We are glad that the provided solution fixed the issue.


Query 2:  I can return values other than the field required for the comboBox from the server side. But how I get these values with javascript? Because fields property only has the following fields. During the add/edit process, I want to take a field other than text and value in the json data from the combox query and send it to the Action during the save process.


Based on your query, you want to get the values sent from the server side in the client side. Your requirement can be achieved by using the ‘change’ event of the EJ2 ComboBox where you can get the entire data of the selected item using the ‘args.itemData’.


Please refer the below code example:


 

comboBoxobj = new ej.dropdowns.ComboBox({

            dataSource: data,

            query: new ej.data.Query().addParams('CustomerID', args.rowData['CustomerID'].toString()).addParams('EmployeeID', args.rowData['EmployeeID']),

            value: args.rowData[args.column.field],

            fields: { text: 'ShipCountry', value: 'ShipCountry' },

            placeholder: 'Select a Country',

            allowCustom: false,

            allowFiltering: true,

            filterType: 'StartsWith',

            change:(args)=> {

                // perform your action here

                console.log(args.itemData);

            }

        });

        comboBoxobj.appendTo(element);

 



Query 3:  ​In the example you gave, the text and value are the same. both ShipCountry. I want to do this: I need to get Text= SKU, Value= Product.Id in return value from my own model to combobox. I also set my column in the Grid to "<e-grid-column field="Product.Id" ". In Add/Edit I have to show the value of Text= SKU from combobox, I have to send Value= Product.Id to Action. After the save, I have to show the Text= SKU in the Grid.


   Based on your query, you want to update another column based on the value selected from one column. We have already documented a similar instance in the below documentation. Kindly refer the below documentation for more details.


Documentation: https://ej2.syncfusion.com/aspnetcore/documentation/grid/how-to/cascading-drop-down-list-with-grid-editing




JT John Taylor July 21, 2023 10:11 PM UTC

Hi,


Query 2: Ok, it worked.


Query 3: Ok, it helped.

Query 4: 
I am using ASP.NET Core Identity. Normally, in .net core mvc, I can show or hide a field in the form using something like "@if (User.IsInRole("Admin"))". How can I hide a field in Grid's edit dialog by role?


Query 5: 

When adding or updating a record from the edit dialog in the grid, how can I post the data in an area outside the grid with the data in the edit dialog?


Br,



JC Joseph Christ Nithin Issack Syncfusion Team July 25, 2023 12:20 PM UTC


Hi John,


  Query 4: I am using ASP.NET Core Identity. Normally, in .net core mvc, I can show or hide a field in the form using something like "@if (User.IsInRole("Admin"))". How can I hide a field in Grid's edit dialog by role?


         Based on your query, you want to hide a field in the editDialog based on some condition. We have already discussed the same in the below documentation. Please refer the documentation for more details.


      Documentiaton: https://ej2.syncfusion.com/aspnetmvc/documentation/grid/editing/dialog-editing#show-or-hide-columns-in-dialog-editing


Query 5: ​When adding or updating a record from the edit dialog in the grid, how can I post the data in an area outside the grid with the data in the edit dialog?


         Based on your query, you want to get the updated data from the grid while saving it to the grid. Your requirement can be achieved by using the parameters of the ‘actionComplete’ event of the EJ2 Grid.


        Please refer the below code example:


 

 

<script>

    function actionComplete(args) {

        if (args.rquestType == "save") {

            // your actions here

        }

    }

</script>

 





Marked as answer
Loader.
Up arrow icon