We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Bind Grid on Change of Multiselect Dropdown

Hi,

How to load data on change of multiselect Grid in ajax call.

Below is my ajax call.

 $.ajax({
            type: "POST",
            url: "/ProjectManager/Projects",
            async: false,
            dataType: "json",
            data: data,
            contentType: "application/json",
            success: function (data) {
                debugger
                var obj = $("#ExistingEmployeesGrid").data("ExistingEmployeesGrid");
                obj.setModel({  //append to the data to dropdownlist   
                    dataSource: data
                });

            },
            error: function () {
                alert('Error Loading Data');
            },
        });   

it is directly going to error function as i think in data i gave grid name what to give in data.

7 Replies

SE Sathyanarayanamoorthy Eswararao Syncfusion Team October 28, 2019 12:00 PM UTC

Hi Naga, 

Thanks for contacting Syncfusion support. 

Query : How to load data on change of multiselect Grid in ajax call. 
 
We have prepared a sample as per your requirement. Please refer the below code example. 

In the below code example, we have sent an ajax call in the change event of the dropdown list with the value selected in the dropdown. Based on the value selected in the dropdown we have fetched the data from the server side and have changed the grid data using the dataSource method in the success event of ajax call. 


<ej-drop-down-list id="selectCompany" datasource="ViewBag.data" change="drpvaluechange"> 
    <e-drop-down-list-fields text="EmployeeID" value="EmployeeID" /> 
</ej-drop-down-list> 
  
<ej-grid id="FlatGrid" datasource="(IEnumerable<object>)ViewBag.datasource" allow-paging="true" load="load" cell-edit="celledit" before-batch-save="beforeSave"> 
    <e-columns> 
        <e-column field="OrderID" header-text="Order ID" is-primary-key="true" text-align="Right" width="75"></e-column> 
        <e-column field="EmployeeID" header-text="Employee ID" text-align="Right" width="75"></e-column> 
        <e-column field="CustomerID" header-text="Customer ID" width="80"></e-column> 
        <e-column field="Freight" header-text="Freight" format="{0:C}" text-align=Right width="75"></e-column> 
        <e-column field="ShipCity" header-text="Ship City" width="110" text-align="Left"></e-column> 
    </e-columns> 
</ej-grid> 
 
 
 
<script> 
    function drpvaluechange(args) { 
        $.ajax({ 
            url: 'GetData', 
            type: 'Get', 
            data: { "ID": args.value }, 
            success: (function (data) { 
                var gridObj = $(".e-grid").ejGrid("instance"); 
                gridObj.dataSource(data); 
            }) 
        }); 
    } 
     
</script> 



Please refer the below documentation link. 


Please refer the below link for the sample. 


Regards, 
Sathyanarayanamoorthy


NP Naga Padmasree October 28, 2019 12:03 PM UTC

Hi,

I got the data from datasource but i am getting the data through datatable.Can you say how can i bind them to columns in ejs grid

View:-
function onSelect(args) {
      
        // Instance created on multiselect component
        var multiselectObj = document.getElementById('ddlFilterEmployee').ej2_instances[0];
        // Get the selected value through Value property
        var selectedValues = (args.itemData[multiselectObj.fields.value]);
        //alert(selectedValues);
        var Empid = selectedValues;
        var data = JSON.stringify({ Empid });// send value
       
        $.ajax({
            type: "POST",
            url: "ProjectManager/GetTimeSheetEntries",
            async: false,
            dataType: "json",
            data: data,
            contentType: "application/json",
            success: function (data) {
                debugger
                var grid = document.getElementById('ExistingEmployeesGrid').ej2_instances[0]; // Grid instance 
                grid.dataSoure = data;// provide the datasource to the Grid 
                
                
            },
            error: function () {
                alert('Error Loading Data');
            },
        });
    }

Controller:-

 IEnumerable data = projectList;
                DataOperations operation = new DataOperations();
                if (dataManager.Search != null && dataManager.Search.Count > 0)
                {
                    data = operation.PerformSearching(data, dataManager.Search);  //Search
                }
                if (dataManager.Sorted != null && dataManager.Sorted.Count > 0) //Sorting
                {
                    data = operation.PerformSorting(data, dataManager.Sorted);
                }
                if (dataManager.Where != null && dataManager.Where.Count > 0) //Filtering
                {
                    data = operation.PerformFiltering(data, dataManager.Where, dataManager.Where[0].Operator);
                }
                List<string> str = new List<string>();
                if (dataManager.Aggregates != null)
                {
                    for (var i = 0; i < dataManager.Aggregates.Count; i++)
                        str.Add(dataManager.Aggregates[i].Field);
                }
                IEnumerable aggregate = operation.PerformSelect(data, str);
                int count = data.Cast<object>().Count();
                if (dataManager.Skip != 0)
                {
                    data = operation.PerformSkip(data, dataManager.Skip);   //Paging
                }
                if (dataManager.Take != 0)
                {
                    data = operation.PerformTake(data, dataManager.Take);
                }
                return dataManager.RequiresCounts ? Json(new { result = data, count = count, aggregate = aggregate }) : Json(data);

            }


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team October 29, 2019 01:50 PM UTC

Hi Naga , 
Thanks for contacting Syncfusion support. 
We suggest you to convert the datatable to list and bind them using the ViewBag. Instead of giving the datasource directly to the dropdown we just convert that into list and then we have bind. The code snippet is showed below for your reference , kindly refer that. 
HomeController.cs 
public IActionResult Index() 
        { 
            DataTable dt = new DataTable("Student"); 
            dt.Columns.Add("value", typeof(Int32)); 
            dt.Columns.Add("text", typeof(string)); 
 
            dt.Rows.Add(1, "MANISH"); 
            dt.Rows.Add(2, "PASTA"); 
            List<detail> studentList = new List<detail>(); 
            for (int i = 0; i < dt.Rows.Count; i++) 
            { 
                detail customer = new detail(); 
                customer.value = Convert.ToInt32(dt.Rows[i]["value"].ToString()); 
                customer.text = dt.Rows[i]["text"].ToString(); 
                studentList.Add(customer); 
            } 
            ViewBag.dataSource = OrdersDetails.GetAllRecords().ToList(); 
            ViewBag.DropDownData = studentList.ToList() ; 
            return View(); 
        } 
 
Index.cshtml 
      <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
      <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120" edit="@(new {create = "create", read = "read", destroy = "destroy", write = "write"})"></e-grid-column> 
      <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column> 
 
<script> 
    var elem; 
    var dObj; 
 
    function create(args) { 
        elem = document.createElement('input'); 
        return elem; 
    } 
 
    function destroy() { 
        dObj.destroy(); 
    } 
 
    function read() { 
        return dObj.text; 
    } 
 
    function write(args) { 
        dObj = new ej.dropdowns.DropDownList({ 
            dataSource: @Html.Raw(Json.Serialize(ViewBag.DropDownData)), 
            fields: { value: 'value', text: 'text' }, 
            floatLabelType: 'Never' 
        }) 
        dObj.appendTo(elem); 
    } 
</script> 
 
 
Detail.cs 
        internal string detailName; 
 
        public string text { get; internal set; } 
        public int value { get; internal set; } 
    } 
} 
Please get back to us if need further assistance. 
Regards, 
Seeni Sakthi Kumar S 



NP Naga Padmasree October 30, 2019 09:24 AM UTC

Thank You For the reply

 function onSelect(args) {
      
        // Instance created on multiselect component
        var multiselectObj = document.getElementById('ddlFilterEmployee').ej2_instances[0];
        // Get the selected value through Value property
        var selectedValues = (args.itemData[multiselectObj.fields.value]);
        //alert(selectedValues);
        //var Empid = selectedValues;
        //var data = JSON.stringify({ Empid: selectedValues });// send value
        var Ajax = new ej.base.Ajax({
            type: "POST",
            url: "ProjectManager/GetProjects",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify([{ EmployeeId: (args.itemData[multiselectObj.fields.value]) }])
        });
        Ajax.send();
        Ajax.onSuccess = function (result) {
            var gridObj = document.getElementById('ExistingEmployeesGrid').ej2_instances[0];//Instance created on Grid
            var data = new ej.data.DataUtil.parse.parseJson(result);
            gridObj.dataSource = data;
           // gridObj.hideSpinner();
        };
        Ajax.onFailure = function (data) {

        }
}

On Selection of Checkbox in EJS Multiselect Dropdown calling a ajax call and sending data from view to controller.But,i am unable to pass the data from view to controller.Null is passing to controller. 


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team October 31, 2019 12:15 PM UTC

Hi Naga,

Please share the controller end code and request messsage displayed in the network tab. So we can check the request sent to the server is correct or not.

Regards,  
Seeni Sakthi Kumar S 



NP Naga Padmasree October 31, 2019 12:20 PM UTC

Controller:-

 public ActionResult GetTimeSheetEntries(string EmployeeId)
        {
            var projectDetailsResult = _projectManagerService.GetAllProjectDetails("0555");

            return Json(new JsonObject(DataTableToJSONWithStringBuilder(projectDetailsResult)));

        }

        public string DataTableToJSONWithStringBuilder(DataTable table)
        {
            var JSONString = new StringBuilder();
            if (table.Rows.Count > 0)
            {
                JSONString.Append("[");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    JSONString.Append("{");
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        if (j < table.Columns.Count - 1)
                        {
                            JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == table.Columns.Count - 1)
                        {
                            JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == table.Rows.Count - 1)
                    {
                        JSONString.Append("}");
                    }
                    else
                    {
                        JSONString.Append("},");
                    }
                }
                JSONString.Append("]");
            }
            return JSONString.ToString();
        }

View:-

function onSelect(args) {

        // Instance created on multiselect component
        var multiselectObj = document.getElementById('ddlFilterEmployee').ej2_instances[0];
        // Get the selected value through Value property
        var selectedValues = (args.itemData[multiselectObj.fields.value]);
        var Ajax = new ej.base.Ajax({
            type: "POST",
            dataType: "json",
            url: "ProjectManager/GetTimeSheetDetails",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ EmployeeId: selectedValues }),
        });
        Ajax.send();
        Ajax.onSuccess = function (result) {

            var gridObj = document.getElementById('TimeSheetGrid').ej2_instances[0];//Grid Instance
            gridObj.showSpinner();//To Show Loading
            var data = new ej.data.DataUtil.parse.parseJson(result);//parse using DataUtil.parse.parseJson method
            //debugger;
            gridObj.dataSource = data.Object;//Provide the datasource to the Grid
            gridObj.allowSorting = true;
            gridObj.load = load();
            // gridObj.gridLines = 0;
            gridObj.hideSpinner();//To Hide Loading
        };
        Ajax.onFailure = function (data) {

        }


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team November 4, 2019 01:54 PM UTC

Hi Naga, 

In your provided code snippet you are sending an ajax request to GetTimeSheetDetails method in the controller. But in the controller code you provided, the method name is given as GetTimeSheetEntries. Either the request is getting sent to the wrong method or the method provided is not defined to receive string format data. So can you once ensure from your end if you are sending request to the correct method and the data type sent in the request and received in the controller are of the same format. In case, you are sending the number as data, received them as int itself in the controller end. Else, receive them as string and ensure to provide the proper method name. 
 
Please share the network tab results and request for the same POST which would be help for us to validate the issue. You can also find the root cause of the problem using the ModelState code as follows. 
 
if(!ModelState.IsValid) 
{ 
  // bad request - Take necessary actions 
} 
 
 
 
If you find any exception details, please share them from the exception messages. 

Regards  
Seeni Sakthi Kumar S 


Loader.
Up arrow icon