Multiselect dropdownlist inside Grid

Hi,

I am trying to add a multiselect dropdownlist inside grid, I would like that ID values selected it stored in my table the following way: 1,5,7,8 and when the grid is populate shows the description values the following way: Germany, England, Canada, Brazil.

Any idea how to do it?

Thanks,

8 Replies

MS Magesh Sabapathi Syncfusion Team April 2, 2020 07:35 AM UTC

Hi Daniel , 

Greetings from syncfusion support 

Query : Multiselect dropdownList inside Grid. 

To achieve this query we suggest to use the edit template method. In that the write function makes you to render the multiselect dropdown and read function makes you to alter the values to store in Grid. Please follow the code snippet and sample for more reference. 

Index.cshtml 

@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col =>{ 
  col.Field("ShipCountry").HeaderText("Ship Country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("150").Add(); 
}) 
<script> 
    var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 

    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function read() { 
        return multiselect.value.join(',');         // The value given in read function must be stored in Grid 
    } 
    function write(args) { 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            placeholder: "Select Tags", 
            fields: { text: 'ID', value: 'country' }, 
       }); 
        multiselect.appendTo(elem); 
    } 

</script> 


Please get back to us if you need further assistance 

Regards 
Magesh 



DA Daniel April 3, 2020 03:05 AM UTC

Hi,

I have added the code but it doesn't work, in my table I have stored the following values: 1, 3 and I expected when the grid it populate show me the description. I notice too when I do double click for edit on the row the previous values are remove from the cell and in the dropdownlist only show the IDs.

@{
    ViewBag.Title = "Control";
}
@using Syncfusion.EJ2


@section StyleSection{
    <link rel='nofollow' href="~/Content/ejthemes/responsive-css/ejgrid.responsive.css" rel="stylesheet" />
}

@section ControlsSection{

    <div class="control-section">
        @{
            Object filterTemplate = new Object();
            filterTemplate = (new { create = "create", read = "read", write = "write" });
        }
        @Html.EJS().Grid("gvQuoteControl").DataSource(dataManager => { dataManager.Url(@Url.Action("UrlDatasource", "QuoteControl")).InsertUrl(@Url.Action("Insert", "QuoteControl")).UpdateUrl(@Url.Action("Update", "QuoteControl")).Adaptor("UrlAdaptor"); }).Height("100%").Columns(col =>
   {
       col.Field("QuoteControlID").HeaderText("ID").IsPrimaryKey(true).Visible(false).AllowEditing(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("50").Add();
       col.Field("QuoteControlCode").HeaderText("No").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Width("150").ValidationRules(new { required = true }).Add();
       col.Field("CustomerID").HeaderText("Client").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Width("350").ValidationRules(new { required = true }).Filter(new { ui = filterTemplate }).ForeignKeyValue("Name").DataSource(ViewBag.DropDownData).Add();
       col.Field("ProviderConsignee").HeaderText("Provider/Consignee").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Width("350").Filter(new { ui = filterTemplate }).ForeignKeyValue("CLIENTPROVIDERNAME").DataSource(ViewBag.DropDownProvider).Add();
       col.Field("ImportExport").HeaderText("Import/Export").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Width("250").Filter(new { ui = filterTemplate }).ForeignKeyValue("TypeIE").DataSource(ViewBag.DropDownImportExport).Add();
       col.Field("DateOfRequest").HeaderText("Date").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).ValidationRules(new { required = true }).Format(new { type = "date", format="dd/MM/yyyy"}).EditType("datetimepickeredit").Width("150").Add();
       col.Field("Origin").HeaderText("Origin").ValidationRules(new { required = true }).Width("300").Add();
       col.Field("Destination").HeaderText("Destination").ValidationRules(new { required = true }).Width("300").Add();
       col.Field("Pcs").HeaderText("Pcs").ValidationRules(new { required = true }).Width("130").Add();
       col.Field("Weight").HeaderText("Weight").Width("150").Add();
       col.Field("AgentOriginOcean").HeaderText("Agents").Edit(new { create = "createAgents", read = "readAgents", destroy = "destroy", write = "writeAgents" }).Width("250").Add();
   }).EditSettings(e => { e.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).AllowPaging().PageSettings(page => page.PageCount(2)).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
     </div>
    <style>
        #typeddl {
            min-width: 100px;
        }
    </style>
    <script>
         var fAgentsData = @Html.Raw(Json.Encode(@ViewData["DropDownAgents"]));
        function createAgents() {
            elem = document.createElement('input');
            return elem;
        }
        function readAgents() {
            return multiselect.value.join(',');         // The value given in read function must be stored in Grid
        }
        function writeAgents(args) {
            multiselect = new ej.dropdowns.MultiSelect({
                dataSource: new ej.data.DataManager(fAgentsData),
                placeholder: "Select Agents",
                fields: { text: 'agentID', value: 'agentName' },
            });
            multiselect.appendTo(elem);
        }

        var dropInstance;
        var dropProviderInstance;
        var dropImportExportInstance;
        var fClienteData = @Html.Raw(Json.Encode(@ViewData["DropDownData"]));
        var fProviderData = @Html.Raw(Json.Encode(@ViewData["DropDownProvider"]));
        var fImportExportData = @Html.Raw(Json.Encode(@ViewData["DropDownImportExport"]));


        function create (args) {
            var flValInput = document.createElement('input');
            flValInput.classList.add('flm-input');
            args.target.appendChild(flValInput);

            dropInstance = new ej.dropdowns.DropDownList({
                dataSource: new ej.data.DataManager(fClienteData),
                fields: { text: 'CustomerID', value: 'Name' },
                placeholder: 'Select a value',
                popupHeight: '250px'
            });
            dropInstance.appendTo(flValInput);

            dropProviderInstance = new ej.dropdowns.DropDownList({
                dataSource: new ej.data.DataManager(fProviderData),
                fields: { text: 'ProviderConsignee', value: 'CLIENTPROVIDERNAME' },
                placeholder: 'Select a value',
                popupHeight: '250px'
            });
            dropProviderInstance.appendTo(flValInput);

            dropImportExportInstance = new ej.dropdowns.DropDownList({
                dataSource: new ej.data.DataManager(fImportExportData),
                fields: { text: 'ImportExport', value: 'TypeIE' },
                placeholder: 'Select a value',
                popupHeight: '250px'
            });
            dropImportExportInstance.appendTo(flValInput);
        }
         function write (args){
             dropInstance.text = args.filteredValue || '';
             dropProviderInstance.text = args.filteredValue || '';
             dropImportExportInstance.text = args.filteredValue || '';
         }
        function read (args) {
            args.fltrObj.filterByColumn(args.column.field, args.operator, dropInstance.text);
            args.fltrObj.filterByColumn(args.column.field, args.operator, dropProviderInstance.text);
            args.fltrObj.filterByColumn(args.column.field, args.operator, dropImportExportInstance.text);
        }
    </script>
}

Thanks,



RR Rajapandi Ravi Syncfusion Team April 6, 2020 12:10 PM UTC

Hi Daniel, 

Thanks for the update 

Query#: when I do double click for edit on the row the previous values are remove from the cell and in the dropdownlist only show the IDs. 

You can show the value of the cell in dropdown while editing by using the value property. Based on your requirement we have prepared a sample and achieved your requirement by using the value property of the Multiselect component. Please refer the below code example and screenshot for more information. 

 
 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  .  .  .  .  .  .  .   
  .  .  .  .  .  .  . 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
   var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
       multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'ID', value: 'country' }, 
            value: args.rowData.ShipCountry.split(',') 
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 


Screenshot: 

Before Editng                                                                                                                    After Editing the form displayed the cell values 
                                      

Regards, 
Rajapandi R


RR Rajapandi Ravi Syncfusion Team April 6, 2020 12:11 PM UTC

Hi Daniel, 

Greetings from syncfusion support 

Based on your query we suspect you like to use Maser-detail Grid, so we have prepared a sample with master-detail Grid for your reference. We have achieved the master-detail Grid by using the “RowSelected” event of Grid. In the RowSelected event, we are updating the detail Grid based on the EmployeeID (primary key) value of the master Grid. Please refer the below code example and sample for more information. 

<div>  
    <B>Master Grid</B>  
    @Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.dataSource).Width("auto").SelectedRowIndex(0).Columns(col =>  
        {  
            col.Field("EmployeeID").HeaderText("EmployeeID").IsPrimaryKey(true).Add();  
            ...  
        }).RowSelected("selected").Render()  
</div>  
<div>  
    <B>Child Grid</B>  
    @Html.EJS().Grid("Grid1").DataSource((IEnumerable<object>)ViewBag.dataSource1).Columns(col =>  
                {  
                    col.Field("EmployeeID").HeaderText("EmployeeID").IsPrimaryKey(true).Add();  
                    ...  
                }).Render()  
</div>  
<script>  
    function selected(args) {  
        var data = @Html.Raw(Json.Encode(ViewBag.datasource));  
        var employeeID = args.data.EmployeeID;  
        var detaildata = new ej.data.DataManager(data).executeLocal(new ej.data.Query().where("EmployeeID""equal", employeeID, false).take(10));  
        var grid = document.getElementById("Grid1").ej2_instances[0];  
        grid.dataSource = new ej.data.DataManager(detaildata.slice(0, 5)).dataSource.json;  
    }  
</script>  
 

From checking your provided view page, we found in your save button click event you are getting the Grid instances like EJ1 Grid. Please refer the below code example for more information. 

 
function btnClick(args) { 
                var grid = $("#DataGrid").ejGrid("instance");    //This is  the EJ1 grid instance 
                grid.batchSave(); 
            } 

And we found you are using BatchURL in Grid Normal edit mode. In normal editing, it will not triggers any method about the Batch. Please refer your below code example for more information. 

 
@Html.EJS().Grid("DataGrid").DataSource(dataManager => { dataManager.Url(@Url.Action("UrlDatasource", "AirQuote")).BatchUrl("BatchUpdate").Adaptor("UrlAdaptor"); }).Columns(col => 
                         { 
                  .   .    .    .    .    .   .   . 
                  .   .     .    .    .     .    .    .                                   
}).EditSettings(e => { e.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).AllowPaging().PageSettings(page => page.PageCount(2)).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 

If you want to use normal edit mode please follow the below documentation for more information. 


If you want to use Batch edit mode. Please follow the below documentation for more information. 


Before we start proceed solution on this query, Please share the below details that will be helpful for us to provide better solution. 

  1. Please confirm you are trying to use a EJ1 or EJ2 Grid.
  2. Please share your exact requirement scenario with detailed expectation.
  3. Share the details about why you render the Grid inside a BeginForm.

Regards, 
Rajapandi R 



DA Daniel replied to Rajapandi Ravi April 9, 2020 02:01 AM UTC

Hi Daniel, 

Thanks for the update 

Query#: when I do double click for edit on the row the previous values are remove from the cell and in the dropdownlist only show the IDs. 

You can show the value of the cell in dropdown while editing by using the value property. Based on your requirement we have prepared a sample and achieved your requirement by using the value property of the Multiselect component. Please refer the below code example and screenshot for more information. 

 
 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  .  .  .  .  .  .  .   
  .  .  .  .  .  .  . 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
   var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
       multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'ID', value: 'country' }, 
            value: args.rowData.ShipCountry.split(',') 
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 


Screenshot: 

Before Editng                                                                                                                    After Editing the form displayed the cell values 
                                      

Regards, 
Rajapandi R

Hi,

I have two questions:

1. How can to do for show the name rather the id?


2. When I try to add a new row the dropdownlist for agents column is missing and the button update and cancel is disabled, what something else should I add?

I am using the following code:

@section ControlsSection{

    <div class="control-section">
        @{
            Object filterTemplate = new Object();
            filterTemplate = (new { create = "create", read = "read", write = "write" });
        }
        @Html.EJS().Grid("gvQuoteControl").DataSource(dataManager => { dataManager.Url(@Url.Action("UrlDatasource", "QuoteControl")).InsertUrl(@Url.Action("Insert", "QuoteControl")).UpdateUrl(@Url.Action("Update", "QuoteControl")).Adaptor("UrlAdaptor"); }).Height("100%").Columns(col =>
   {
       col.Field("QuoteControlID").HeaderText("ID").IsPrimaryKey(true).Visible(false).AllowEditing(false).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("50").Add();
       col.Field("QuoteControlCode").HeaderText("No").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).Width("150").ValidationRules(new { required = true }).Add();
       col.Field("DateOfRequest").HeaderText("Date").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Center).ValidationRules(new { required = true }).Format(new { type = "date", format="dd/MM/yyyy"}).EditType("datetimepickeredit").Width("150").Add();
       col.Field("Origin").HeaderText("Origin").ValidationRules(new { required = true }).Width("300").Add();
       col.Field("Destination").HeaderText("Destination").ValidationRules(new { required = true }).Width("300").Add();
       col.Field("Pcs").HeaderText("Pcs").ValidationRules(new { required = true }).Width("130").Add();
       col.Field("Weight").HeaderText("Weight").Width("150").Add();
       col.Field("AgentOriginOcean").HeaderText("Agents").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("250").Add();
   }).EditSettings(e => { e.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).AllowPaging().PageSettings(page => page.PageCount(2)).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
     </div>
    <style>
        #typeddl {
            min-width: 100px;
        }
    </style>
    <script>
         var elem;
        var multiselect;
         var fAgentsData = @Html.Raw(Json.Encode(@ViewData["DropDownAgents"]));
        function create() {
            elem = document.createElement('input');
            return elem;
        }
        function destroy() {
            multiselect.destroy();
        }
        function read() {
            return multiselect.value.join(',');
        }
        function write(args) {
            multiselect = new ej.dropdowns.MultiSelect({
                dataSource: new ej.data.DataManager(fAgentsData),
                placeholder: "Select Agents",
                fields: { text: 'agentID', value: 'agentName' },
                value: args.rowData.AgentOriginOcean.split(',')
            });
            multiselect.appendTo(elem);
        }
    </script>
}

Thanks,


RR Rajapandi Ravi Syncfusion Team April 9, 2020 12:53 PM UTC

Hi Daniel, 

Thanks for the update 

Query#: How can to do for show the name rather the id? 

You can show the name instead of the id in dropdown while editing by using the fields property. Based on your requirement we have prepared a sample and achieved your requirement by using the fields property of the Multiselect component. 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. Please refer the below code example, screenshot and documentation for more information. 

 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  . . . . . . . .  . .  . 
  . . . . . . . .  . .  .  
  col.Field("ShipCountry").HeaderText("Ship Country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("150").Add(); 
 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
    var arr = []; 
    var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
        arr.push(args.rowData.ShipCountry) 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'country', value: 'country' }, 
            value: Array.isArray(args.rowData.ShipCountry) ? args.rowData.ShipCountry : arr   
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 
 
  

Screenshot:  

 


Query#: When I try to add a new row the dropdownlist for agents column is missing and the button update and cancel is disabled, what something else should I add? 

From checking your query, we found the that issue causes because of the split method while adding the record. To overcome the issue we suggest you to use the below way to achieve your requirement. Please follow the below code example, screenshot for more information. 

 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  . . . . . . . .  . .  . 
  . . . . . . . .  . .  .  
  col.Field("ShipCountry").HeaderText("Ship Country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("150").Add(); 
 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
    var arr = []; 
    var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
        arr.push(args.rowData.ShipCountry) 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'country', value: 'country' }, 
            value: Array.isArray(args.rowData.ShipCountry) ? args.rowData.ShipCountry : arr   //here you have to set the array value 
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 
 
  
Screenshot: 

 


For your both queries we have prepared a sample and for your reference we have attached the documentation of Multiselect component.  Please refer the below sample and documentation for more information. 



Regards, 
Rajapandi R


DA Daniel replied to Rajapandi Ravi April 9, 2020 10:21 PM UTC

Hi Daniel, 

Thanks for the update 

Query#: How can to do for show the name rather the id? 

You can show the name instead of the id in dropdown while editing by using the fields property. Based on your requirement we have prepared a sample and achieved your requirement by using the fields property of the Multiselect component. 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. Please refer the below code example, screenshot and documentation for more information. 

 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  . . . . . . . .  . .  . 
  . . . . . . . .  . .  .  
  col.Field("ShipCountry").HeaderText("Ship Country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("150").Add(); 
 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
    var arr = []; 
    var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
        arr.push(args.rowData.ShipCountry) 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'country', value: 'country' }, 
            value: Array.isArray(args.rowData.ShipCountry) ? args.rowData.ShipCountry : arr   
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 
 
  

Screenshot:  

 


Query#: When I try to add a new row the dropdownlist for agents column is missing and the button update and cancel is disabled, what something else should I add? 

From checking your query, we found the that issue causes because of the split method while adding the record. To overcome the issue we suggest you to use the below way to achieve your requirement. Please follow the below code example, screenshot for more information. 

 
@Html.EJS().Grid("SelectionAPI").DataSource((IEnumerable<object>)ViewBag.datasource).AllowSelection().Columns(col => 
{ 
  . . . . . . . .  . .  . 
  . . . . . . . .  . .  .  
  col.Field("ShipCountry").HeaderText("Ship Country").Edit(new { create = "create", read = "read", destroy = "destroy", write = "write" }).Width("150").Add(); 
 
}).AllowPaging().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 
<script> 
 
    var elem; 
    var multiselect; 
    var arr = []; 
    var datas = [{ country: "Germany", ID: 1 }, 
                 { country: "England", ID: 5 }, 
                 { country: "Canada", ID: 7 }, 
                 { country: "Brazil", ID: 8}]; 
 
    function create() { 
        elem = document.createElement('input'); 
        return elem; 
    } 
    function destroy() { 
        multiselect.destroy(); 
    } 
    function read() { 
        return multiselect.value.join(','); 
    } 
    function write(args) { 
        arr.push(args.rowData.ShipCountry) 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: datas, 
            fields: { text: 'country', value: 'country' }, 
            value: Array.isArray(args.rowData.ShipCountry) ? args.rowData.ShipCountry : arr   //here you have to set the array value 
        }); 
        multiselect.appendTo(elem); 
    } 
 
</script> 
 
  
Screenshot: 

 


For your both queries we have prepared a sample and for your reference we have attached the documentation of Multiselect component.  Please refer the below sample and documentation for more information. 



Regards, 
Rajapandi R

Hi Rajapandi,

Thanks for the help,

Two thing more:

1. If I put the following:

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

When I will to save the grid in the controller I will only to see the name of the country, I need to see in the client side the country name and the controller I need to see the countryId.

2. How can to do unselect the previous values that I have selected in the dropdownlist?

Thanks,




SK Sujith Kumar Rajkumar Syncfusion Team April 10, 2020 10:26 AM UTC

Hi Daniel, 
 
Query – 1: When I will to save the grid in the controller I will only to see the name of the country, I need to see in the client side the country name and the controller I need to see the countryId. 
 
You can achieve this requirement by defining the multi-select data in the controller-part and when the insert/update operations is performed in the controller you can compare the data value with the dropdown data and based on that access the id value. This is demonstrated in the below code snippet, 
 
public ActionResult Update(CRUDModel myObject) 
        { 
            var ord = myObject.Value; 
            // Multi-select data is retrieved 
            var dropdata = DropDownData.GetAllRecords().ToList(); 
            // The selected value is compared with the multi-select data to return the corresponding result 
            var selectedData = dropdata.Where(dd => dd.Country == ord.ShipCountry).FirstOrDefault(); 
            // ID value is selected from the resultant data 
            var countryId = selectedData.CountryID; 
                 . 
                 . 
                 . 
            return Json(myObject.Value); 
 
        } 
 
// Multi-select data defined in the controller part 
public class DropDownData 
        { 
            public static List<DropDownData> dropdata = new List<DropDownData>(); 
            public DropDownData() 
            { 
 
            } 
            public DropDownData(int CountryID, string Country) 
            { 
                this.CountryID = CountryID; 
                this.Country = Country; 
            } 
 
            public static List<DropDownData> GetAllRecords() 
            { 
                if (dropdata.Count() == 0) 
                { 
 
                    dropdata.Add(new DropDownData(1, "Brazil")); 
                    dropdata.Add(new DropDownData(2, "Germany")); 
                    dropdata.Add(new DropDownData(3, "England")); 
                    dropdata.Add(new DropDownData(4, "Canada")); 
                } 
                return dropdata; 
            } 
 
            public int CountryID { get; set; } 
            public string Country { get; set; } 
        } 
 
This multi-select data can be bound to the component in the client-side using JSON Encode method. 
 
function write(args) { 
        var arr = (args.rowData["ShipCountry"] == null ? "" : args.rowData["ShipCountry"]); 
        multiselect = new ej.dropdowns.MultiSelect({ 
            dataSource: @Html.Raw(Json.Encode(@ViewBag.dropData)), 
            fields: { text: 'Country', value: 'Country' }, 
            value: Array.isArray(arr) || arr.length == 0 ? arr : arr.split(',') 
        }); 
        multiselect.appendTo(elem); 
} 
 
We have modified the previously provided sample based on this which you can find below, 
 
 
Query – 2: How can to do unselect the previous values that I have selected in the dropdownlist? 
 
From your query we suspect your requirement is to remove the previous value on editing in the multi-select dropdown list. If so you can achieve this by not specifying the value property for the multi-select component rendered in the edit params write method. 
 
If we misunderstood your query or if you require any further assistance please get back to us. 
 
Regards, 
Sujith R 


Loader.
Up arrow icon