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

Change DataGrid DataSource on the fly with JavaScript

I have the following grid working fine with no problems:


<script>
    function load(args) {
        this.columns[1].format = { type: 'date', format: 'dd/MM/yyyy' };  // set your customize date format based on your column
    }

    function toolbarClick(args) {
        var gridObj = document.getElementById("SaldosMXgrid").ej2_instances[0];
        if (args.item.id === 'SaldosMXgrid_pdfexport') {
            gridObj.pdfExport();
        }
        if (args.item.id === 'SaldosMXgrid_excelexport') {
            gridObj.excelExport();
        }
    }

    function refresh(e) {
        if (e.requestType == "save") {
            var grid = document.getElementById("SaldosMXgrid").ej2_instances[0];
            grid.refresh();
        }
    }
</script>

<h2>Saldos Moneda Nacional</h2>
<p>
    <div id="menubuttons">
        <ejs-button id="btn" content="Importar Saldos MXN" type="button" onclick='ImportarSaldosMXN()' style="margin-top:15px;"></ejs-button>
    </div>
</p>
<hr />

@{
    var chilDataManager = new Syncfusion.EJ2.DataManager()
    {

        Adaptor = "UrlAdaptor",
        Url = "/Saldos/FacturasRelacionadasgrid_Read/ ",
        RequestType = "Post",
        CrossDomain = true,
        InsertUrl = "/Saldos/FacturasRelacionadasgrid_Create/",
        RemoveUrl = "/Saldos/FacturasRelacionadasgrid_Delete/"
    };

    var childGrid = new Syncfusion.EJ2.Grids.Grid()
    {
        DataSource = chilDataManager,
        QueryString = "BalanceID",
        ActionBegin = "begin",
        Toolbar = new List<string>()
            {
                new string("Add"),
                new string("Delete"),
                new string("Cancel"),
                new string("Update")
            },
        EditSettings =  new Syncfusion.EJ2.Grids.GridEditSettings()
        {
            AllowAdding = true,
            AllowDeleting = true
        },
        Columns = new List<Syncfusion.EJ2.Grids.GridColumn>
{
            new Syncfusion.EJ2.Grids.GridColumn(){ Field = "BalancesCfdiRelationID", Visible = false, IsPrimaryKey = true, IsIdentity = true },
            new Syncfusion.EJ2.Grids.GridColumn(){ Field = "BalanceID", Visible = false, DefaultValue = "$ BalanceID" },
            new Syncfusion.EJ2.Grids.GridColumn(){ Field = "cfdiID", HeaderText = "Factura", ForeignKeyValue = "Factura", ForeignKeyField = "cfdiID", DataSource = ViewBag.Facturas },
        }
    };
    }
<script>
    function begin(args) {
        if (args.requestType == "save") {
            var value = this.parentDetails.parentKeyFieldValue;
            args.data.BalanceID = value;
        }
    }     
</script>


<div id="contenido">
    <br />
    <ejs-grid id="SaldosMXgrid" childGrid="childGrid" load="load"  allowExcelExport="true" allowSorting="true" allowReordering="true" allowFiltering="true" allowPaging="true" toolbarClick="toolbarClick" toolbar="@(new List<string>() { "ExcelExport", "Search", "Print", "Cancel", "Update" })">
        <e-data-manager id="dataManager" adaptor="UrlAdaptor" url="/Saldos/SaldosMXgrid_Read" updateUrl="/Saldos/SaldosMXgrid_Update" requestType="Post"></e-data-manager>
        <e-grid-editSettings allowDeleting="false" allowEditing="true" allowAdding="false" mode="Normal" showConfirmDialog="true"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="BalanceID" isPrimaryKey="true" visible="false"></e-grid-column>
            <e-grid-column field="TransactionDate" type="date" headerText="Fecha" width="110" allowEditing="false"></e-grid-column>
            <e-grid-column field="TransactionReference" headerText="Referencia" width="610" allowEditing="false"></e-grid-column>
            <e-grid-column field="Withdraw" headerText="Cargos" width="120" format="c2" allowEditing="false"></e-grid-column>
            <e-grid-column field="WithdrawComments" headerText="Comentarios" allowResizing="true" width="300" allowEditing="true"></e-grid-column>
            <e-grid-column field="Deposit" headerText="Abono" width="280" format="c2" allowResizing="true" allowEditing="false"></e-grid-column>
            <e-grid-column field="DepositComments" headerText="Comentarios" width="300" allowEditing="true"></e-grid-column>
            <e-grid-column field="BalanceAmount" headerText="Saldo" format="c2" allowResizing="true" visible="true" width="150" allowEditing="false"></e-grid-column>
        </e-grid-columns>
    </ejs-grid>
    <ejs-scripts></ejs-scripts>
</div>


This is the controller read action:

 public IActionResult SaldosMXgrid_Read([FromBody]DataManagerRequest dm)
        {
            IEnumerable<Balances> DataSource;
            using (var context = new CotizadorTodashContext())
            {
                var CompanyID = context.AccountingUsers.FirstOrDefault(p => p.userLogin == User.Identity.Name).CompanyID;
                DataSource = context.Balances.Where(p => p.CompanyID == CompanyID && p.BalanceCurrency == "MXN").OrderBy(p => p.BalanceID).OrderByDescending(p => p.TransactionDate).ToList();
                foreach(var item in DataSource)
                {
                    item.Company = null;
                }
            }
            DataOperations operation = new DataOperations();
            if (dm.Search != null && dm.Search.Count > 0)
            {
                DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search 
            }
            int count = 0;
            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);
            }

            else
            {
                count = DataSource.Cast<Balances>().Count();
            }
            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);
        }



What i need to do is, to change the read Url on the fly with JavaScript, to reload the grid with new data, according the user input. I can create a new DataManager with JS, and assign it to the datagrid, but, it doesn't hit the controller action unless i change the "[FromBody]" tag to "[FromForm]", but in that case, the data returns correctly but the grid doesn´t show it.


Can you help me with that? 

BTW..Sorry for the bad english


5 Replies

JA Javier A Aguilera April 30, 2019 11:54 PM UTC

I figured a working way to change the grid datasource on the fly as described before.

In the view, i add this javascript code:

    function filterMonthData(mes) { 
        var grid = document.getElementById("SaldosMXgrid").ej2_instances[0];
         $.ajax({
            url: "/Saldos/SaldosMXgrid_ReadFilter",
             type: "POST",
            data: { vFilter: mes + '-' + $("#anio").val() },
            success: function (data) {
                grid.dataSource = data;
            }
        });
    }

This is the controller action:
 public IActionResult SaldosMXgrid_ReadFilter([FromForm] DataManagerRequest dm, string vFilter)
        {
            string[] values = vFilter.Split("-");
            int mes = DateTime.Now.Month;
            if (values[0].Length > 0)
            {
                mes = Convert.ToInt16(values[0]);
            }
            int anio = DateTime.Now.Year;
            if (values[1] != "0000")
            {
                anio = Convert.ToInt16(values[1]);
            }

            IEnumerable<Balances> DataSource;
            using (var context = new CotizadorTodashContext())
            {
                var CompanyID = context.AccountingUsers.FirstOrDefault(p => p.userLogin == User.Identity.Name).CompanyID;
                DataSource = context.Balances.Where(p => p.CompanyID == CompanyID && p.BalanceCurrency == "MXN" && p.TransactionDate.Year == anio && p.TransactionDate.Month == mes).OrderBy(p => p.BalanceID).OrderByDescending(p => p.TransactionDate).ToList();


                foreach (var item in DataSource)
                {
                    item.Company = null;
                }
            }
            DataOperations operation = new DataOperations();
            if (dm.Search != null && dm.Search.Count > 0)
            {
                DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search 
            }
            int count = 0;
            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);
            }

            else
            {
                count = DataSource.Cast<Balances>().Count();
            }
            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);
        }

It actually works, the grid are now showing the controller action response, but now the problem is......i have lost the hability to update a record in the grid....So the new question is, How can i add back the update url to my grid?


RN Rahul Narayanasamy Syncfusion Team May 1, 2019 11:28 AM UTC

Hi Javier, 
 
We have analyzed your requirement. We suggest you to use the “addParams” method. You can send additional parameter to the data request by using “addParams” method of Query class. Please refer the below documentations, 
 
Please get back to us if you need further assistance. 

Regards, 
Rahul N. 



JA Javier A Aguilera May 1, 2019 04:35 PM UTC

Hi.
i´m trying this way:

var grid = document.getElementById("SaldosMXgrid").ej2_instances[0];
grid.query = new ej.data.Query().addParams('vFilter', '01-2019');
grid.refresh();

In browsers console i see this on the request header:



But now......I actually don´t know how to get this value on the controller side =(

Can you help me with that?



JA Javier A Aguilera May 1, 2019 04:55 PM UTC

I think i got it.

I create a new DataManagerRequest class, like this:

 public class BalancesDataManagerRequest : DataManagerRequest
    {
        [HtmlAttributeName("vFilter")]
        [JsonProperty("vFilter")]
        public string vFilter { get; set; }
    }

then changed my controller action :

 public IActionResult SaldosMXgrid_Read([FromBody]BalancesDataManagerRequest dm)

and now i have the new param:


=)


HJ Hariharan J V Syncfusion Team May 2, 2019 12:24 PM UTC

Hi Javier, 
 
Thanks for your update.  
  
We are happy to hear that your issue has solved.  
   
Regards, 
Hariharan 


Loader.
Live Chat Icon For mobile
Up arrow icon