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. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Calculate total for row and refresh grid after insert command

Thread ID:

Created:

Updated:

Platform:

Replies:

145583 Jun 28,2019 07:19 PM UTC Jul 10,2019 08:44 AM UTC ASP.NET Core - EJ 2 5
loading
Tags: DataGrid
Javier A Aguilera
Asked On June 28, 2019 07:19 PM UTC

Good afternoon gentleman,

I'm trying to calculate the total amount for each row, i have for each row the amount data and Unit price and i need to automatic calculate the total which I think is something like:

          rowTotal = (rowCant * rowUnitPrice) - rowDiscount;
          document.querySelector("#ConfiguracionPACGridImporte").value = rowTotal;

The thing is that I'm not sure how or where to trigger this action. 

Second question is, after I register a new record the grid is not refreshing itself, how can I auto refresh it after I click update button?


In advice, I give my thanks, You have a really good product and an Excellent support service!


MY CODE:

<ejs-grid id="ConfiguracionPACGrid" actionComplete="refresh" toolbar="@(new List<string>() { "Add","Delete","Update", "Cancel" })">
    <e-data-manager adaptor="UrlAdaptor" url="/Facturacion/gridConceptosXFacturar_Read" requestType="Post" insertUrl="/Facturacion/gridConceptosXFacturar2_Create/?iva=@iva" updateUrl="/Administracion/ConfiguracionPACGrid_Update" removeUrl="/Administracion/ConfiguracionPACGrid_Destroy"></e-data-manager>
    <e-grid-editSettings allowDeleting="true" allowEditing="true" allowAdding="true" mode="Normal" showConfirmDialog="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="ConceptoCfdiID" isPrimaryKey="true" visible="false"></e-grid-column>
        <e-grid-column field="cfdiID" headerText="cfdiID" width="90" visible="false" defaultValue="@varidNuevo"></e-grid-column>
        @*<e-grid-column field="ProductName" headerText="Producto" width="180"></e-grid-column>*@
        <e-grid-column field="ProductName" headerText="Producto" foreignKeyValue='ProductName' dataSource="@ViewBag.ForeignData" edit="@(new {create="create", read="read", destroy="destroy", write="write"})" width="180"></e-grid-column>
        <e-grid-column field="ClaveProdServ" headerText="Clave Producto Servicio" width="180"></e-grid-column>
        <e-grid-column field="Descripcion" headerText="Descripción" width="300"></e-grid-column>
        <e-grid-column field="ClaveUnidad" headerText="Clave Unidad" width="150"></e-grid-column>
        <e-grid-column field="Unidad" headerText="Unidad" width="150"></e-grid-column>
        <e-grid-column field="ValorUnitario" headerText="Valor Unitario" editType="numericedit" format="C2" width="150"></e-grid-column>
        <e-grid-column field="Cantidad" headerText="Cantidad" editType="numericedit" format="C2" edit="@(new {create="createCant", read="readCant", destroy="destroyCant", write="writeCant"})" width="150"></e-grid-column>
        <e-grid-column field="Descuento" headerText="Descuento" editType="numericedit" format="C2" width="150"></e-grid-column>
        <e-grid-column field="Importe" headerText="Importe" editType="numericedit" format="C2" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<ejs-scripts></ejs-scripts>


<script>
    var elem;
    var dObj = @Json.Serialize(ViewBag.ForeignData);

    function create(args) {
        elem = document.createElement('input');
        return elem; 
    }

    function read(args) { 
        return dObj.value; 
    }

    function destroy () {
        dObj.destroy();
    }

    function write (args) { 
        dObj = new ej.dropdowns.AutoComplete({ 
            dataSource: @Html.Raw(Json.Serialize(ViewBag.ForeignData)), 
            fields: { value: 'ProductName' }, 
            value: args.rowData[args.column.field], 
            change: (e) => {
                   $.ajax({ 
                    type: 'POST', 
                    url: '@Url.Action("FindProductData", "Facturacion")', 
                    data: { 
                        productName: e.value 
                    }, 
                       success: function (response) {
                           document.querySelector("#ConfiguracionPACGridClaveProdServ").value = response._ClaveProdServ;
                           document.querySelector("#ConfiguracionPACGridDescripcion").value = response._Descripcion;
                           document.querySelector("#ConfiguracionPACGridClaveUnidad").value = response._ClaveUnidad;
                           document.querySelector("#ConfiguracionPACGridUnidad").value = response._Unidad;
                           document.querySelector("#ConfiguracionPACGridValorUnitario").value = response._ValorUnitario;
                    } 
                });  
            }
        });
        dObj.appendTo(elem);
    }



    var elemCant;
    var dObjCant = @Json.Serialize(ViewBag.ForeignData);

    function createCant(args) {
        alert("entro");
        elemCant = document.createElement('input');
        return elemCant; 
    }

    function readCant(args) { 
        return dObjCant.value; 
    }

    function destroyCant () {
        dObjCant.destroy();
    }

    function writeCant(args) { 
        alert("hi");
        var rowCant = 0;
        var rowUnitPrice = 0;
        var rowDiscount = 0;
        var rowTotal = 0;
        try { rowCant = document.querySelector("#ConfiguracionPACGridCantidad").value; } catch (err) { rowCant = 0; }
        try { rowUnitPrice = document.querySelector("#ConfiguracionPACGridValorUnitario").value; } catch (err) { rowUnitPrice = 0; }
        try { rowDiscount = document.querySelector("#ConfiguracionPACGridDescuento").value; } catch (err) { rowDiscount = 0; }
        
        rowTotal = (rowCant * rowUnitPrice) - rowDiscount;
        document.querySelector("#ConfiguracionPACGridImporte").value = rowTotal;
    }


</script>

<script>
    function refresh(e) {
        
        alert(args.requestType);

        if (args.requestType == "save") {
            var grid = document.getElementById("gridConceptosXFacturar").ej2_instances[0];
            grid.refresh();
        }
    }




Pavithra Subramaniyam [Syncfusion]
Replied On July 1, 2019 12:03 PM UTC

Hi Javier, 
 
Thanks for contacting Syncfusion support. 
 
Query #1: I'm trying to calculate the total amount for each row, i have for each row the amount data and Unit price and i need to automatic calculate the total which I think is something like 
 
From your code, we found that you have tried to provide the calculated value to “Importe” column numericTextBox while changing the value in “cantidad” column. So, we suggest to bind the “input”  event to “cantidad” column input textbox and use that event to provide a calculated value to “Importe” column numericTextBox through the instance. Please refer the below code snippet, 
 
<ejs-grid id="Grid" allowPaging="true" actionComplete="actionComplete" toolbar="@(new List<string>() { "Add","Delete","Update", "Cancel" })"> 
    <e-data-manager url="/Home/UrlDatasource" insertUrl="/Home/Insert" updateUrl="/Home/Update" removeUrl="/Home/Remove" adaptor="UrlAdaptor"></e-data-manager> 
    <e-grid-editSettings allowAdding="true" allowEditing="true" allowDeleting="true" mode="Normal"></e-grid-editSettings> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" width="100"></e-grid-column> 
        <e-grid-column field="Freight" headerText="Freight" format="C2" width="120"></e-grid-column> 
        <e-grid-column field="EmployeeID" headerText="Employee ID" editType="numericedit" format="C2" width="120"></e-grid-column> 
    </e-grid-columns> 
</ejs-grid> 
 
<script type="text/javascript"> 
    function actionComplete(args) { // Grid actionComplete event 
        if (args.requestType == "beginEdit") {  
            args.form.querySelector("#GridFreight").addEventListener("input", function (e) { // bind the input event to Freight column input textbox 
                var value = parseFloat(this.value); 
                value = value * 10; 
                var numericTextBox = args.form.querySelector("#GridEmployeeID").ej2_instances[0]; // numericTextBox instance 
                numericTextBox.value = value; // Change the numericTextBox value with calculated value through the instance 
            }) 
        } 
    } 
</script> 
 
In this code, we have bound the “input” event for Freight column input textbox by using the Grid actionComplete event. After that we have used this “input” event to change the EmployeeID column numericTextBox value. 
 
Query #2: Second question is, after I register a new record the grid is not refreshing itself, how can I auto refresh it after I click update button? 
 
By default, Grid will automatically refresh when we add the new record in Grid. But while using the remote data, we must need to return the newly added record from the controller to Grid. So, please ensure whether added record is properly returned or not. You can use browser network tab to ensure the controller returned value. 
 
For your convenience, we have prepared the sample with this both queries and you can find that sample from the below link, 
 
 
If we misunderstood your query, please share more details about requirement. This will help us to provide a better solution for your issue as early as possible. 
 
Regards,  
Pavithra S. 
 


Javier A Aguilera
Replied On July 1, 2019 08:34 PM UTC

Thank you very much for your fast answer, I really appreciate it. 

Unfortunately, I still havent reach the spected functionality (probably my bad), can you please help me out? What am I missing?


The points are still the same:
1) I need to calculate "Importe" with "Cantidad" and "ValorUnitario" (currently im trying to multiply by 10 for ease)
2) The I click Update button after typing all fields for a new record I need the grid to refresh its content (but still i cant get that to work)

In the second point, I just discover a difference between your example and mine, in mine i cannot reach actioncomplete alert of "save" when i click the button of Update....probable my error is in the controller action, but i dont get errors in the console while running this point.

In advance, thank you for your support


///////////////////////  MY VIEW /////////////////////////////////////////////////////////////////////

@model int
@{
    ViewBag.Title = "Generar Factura Paso2";
    Layout = null;
    var idNuevo = Model.ToString();
    int varidNuevo = 0;
    var iva = Convert.ToString(ViewBag.iva);
    if (null != idNuevo)
    {
        if ("" != idNuevo)
        {
            varidNuevo = int.Parse(idNuevo);
        }
    }
}

<br />
<script>
    var elem;
    var dObj = @Json.Serialize(ViewBag.ForeignData);

    function create(args) {
        elem = document.createElement('input');
        return elem;
    }

    function read(args) {
        return dObj.value;
    }

    function destroy () {
        dObj.destroy();
    }

    function write (args) {
        dObj = new ej.dropdowns.AutoComplete({
            dataSource: @Html.Raw(Json.Serialize(ViewBag.ForeignData)),
            fields: { value: 'ProductName' },
            value: args.rowData[args.column.field],
            change: (e) => {
                   $.ajax({
                    type: 'POST',
                    url: '@Url.Action("FindProductData", "Facturacion")',
                    data: {
                        productName: e.value
                    },
                       success: function (response) {
                           document.querySelector("#ConfiguracionPACGridClaveProdServ").value = response._ClaveProdServ;
                           document.querySelector("#ConfiguracionPACGridDescripcion").value = response._Descripcion;
                           document.querySelector("#ConfiguracionPACGridClaveUnidad").value = response._ClaveUnidad;
                           document.querySelector("#ConfiguracionPACGridUnidad").value = response._Unidad;
                           document.querySelector("#ConfiguracionPACGridValorUnitario").value = response._ValorUnitario;
                    }
                });
            }
        });
        dObj.appendTo(elem);
    }

    
    function actionComplete(args) { // Grid actionComplete event
        alert(args.requestType);
        if (args.requestType == "beginEdit") {
            args.form.querySelector("#ConfiguracionPACGridCantidad").addEventListener("input", function (e) {
                var value = parseFloat(this.value);
                value = value * 10;
                var numericTextBox = args.form.querySelector("#ConfiguracionPACGridImporte").ej2_instances[0];
                numericTextBox.value = value;
                document.querySelector("#ConfiguracionPACGridValorUnitario").value = value;
            })
        }
    }
    
</script>

<h3>Agregar Conceptos</h3>

<ejs-grid id="ConfiguracionPACGrid" actionComplete="actionComplete" toolbar="@(new List<string>() { "Add","Delete","Update", "Cancel" })">
    <e-data-manager adaptor="UrlAdaptor" url="/Facturacion/gridConceptosXFacturar_Read" requestType="Post" insertUrl="/Facturacion/gridConceptosXFacturar2_Create/?iva=@iva" updateUrl="/Administracion/ConfiguracionPACGrid_Update" removeUrl="/Administracion/ConfiguracionPACGrid_Destroy"></e-data-manager>
    <e-grid-editSettings allowDeleting="true" allowEditing="true" allowAdding="true" mode="Normal" showConfirmDialog="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="ConceptoCfdiID" isPrimaryKey="true" visible="false"></e-grid-column>
        <e-grid-column field="cfdiID" headerText="cfdiID" width="90" visible="false" defaultValue="@varidNuevo"></e-grid-column>
        <e-grid-column field="ProductName" headerText="Producto" foreignKeyValue='ProductName' dataSource="@ViewBag.ForeignData" edit="@(new {create="create", read="read", destroy="destroy", write="write"})" width="180"></e-grid-column>
        <e-grid-column field="ClaveProdServ" headerText="Clave Producto Servicio" width="180"></e-grid-column>
        <e-grid-column field="Descripcion" headerText="Descripción" width="300"></e-grid-column>
        <e-grid-column field="ClaveUnidad" headerText="Clave Unidad" width="150"></e-grid-column>
        <e-grid-column field="Unidad" headerText="Unidad" width="150"></e-grid-column>
        <e-grid-column field="ValorUnitario" headerText="Valor Unitario" editType="numericedit" format="C2" width="150"></e-grid-column>
        <e-grid-column field="Cantidad" headerText="Cantidad" format="C2" width="150"></e-grid-column>
        <e-grid-column field="Descuento" headerText="Descuento" editType="numericedit" format="C2" width="150"></e-grid-column>
        <e-grid-column field="Importe" headerText="Importe" editType="numericedit" format="C2" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<ejs-scripts></ejs-scripts>


///////////////////////  MY CONTROLLER  ///////////////////////

[HttpPost]
        public IActionResult gridConceptosXFacturar2_Create([FromBody]CRUDModel<f4_ConceptosCFDIXgenerar> obj, int iva)
        {
            if (obj != null && ModelState.IsValid)
            {
                using (var context = new CotizadorTodashContext())
                {
                    context.f4_ConceptosCFDIXgenerar.Add(obj.Value);
                    context.SaveChanges();

                    var nuevoImpuesto = new f4_ImpuestosConceptosCFDIXgenerar
                    {
                        Base = obj.Value.Importe,
                        Impuesto = "002",
                        TasaOCuota = Convert.ToDecimal((Convert.ToDecimal(iva) / 100)),
                        TipoFactor = "Tasa",
                        TrasladoTasa = "Traslado",
                        Importe = (obj.Value.Importe * ((Convert.ToDecimal(iva)) / 100)),
                        ConceptoCfdiID = obj.Value.ConceptoCfdiID
                    };
                    context.f4_ImpuestosConceptosCFDIXgenerar.Add(nuevoImpuesto);
                    context.SaveChanges();
                }
            }
            return Json(obj.Value);
        }




Pavithra Subramaniyam [Syncfusion]
Replied On July 2, 2019 07:18 AM UTC

Hi Javier, 
 
Query #1:  I need to calculate "Importe" with "Cantidad" and "ValorUnitario" (currently im trying to multiply by 10 for ease) 
 
From you code we found that you want to update numericTextBox values in “ValorUnitario” and “Importe” columns based on the updated “Cantidad” column value. You can achieve this requirement like as below code snippet, 
 
function actionComplete(args) { // Grid actionComplete event 
        alert(args.requestType); 
        if (args.requestType == "beginEdit") { 
            args.form.querySelector("#ConfiguracionPACGridCantidad").addEventListener("input", function (e) { 
                var value = parseFloat(this.value); 
                value = value * 10; 
                var CantidadNumericTextBox = args.form.querySelector("#ConfiguracionPACGridImporte").ej2_instances[0]; 
                CantidadNumericTextBox.value = value; // Change the Importe numericTextBox value based on Cantidad 
                var UnitarioNumericTextBox = args.form.querySelector("#ConfiguracionPACGridValorUnitario").ej2_instances[0]; 
                UnitarioNumericTextBox.value = value; // Change the ValorUnitario numericTextBox value based on Cantidad 
            }) 
        } 
    } 
 
If you will face any issue while applying this solution, please share the issue details (like screenshot or video demonstration) to us  for further assistance. 
 
Query #2:  I just discover a difference between your example and mine, in mine i cannot reach actioncomplete alert of "save" when i click the button of Update…probable my error is in the controller action, but i dont get errors in the console while running this point. 
 
First we would like to inform that we could not understood this query properly. So, we suspect that you want to find the failed actions in Grid. You can use actionFailure event to achieve this requirement. You can get the issue details in this event arguments. If you need further assistance, then please share this event argument details and controller issue details to us. 
 
Documentation for actionFailure event, 
 
 
Regards, 
Pavithra S. 
  


Javier A Aguilera
Replied On July 9, 2019 05:31 PM UTC

Worked out very good! Thanks, same as always, your support is a great service.

Seeni Sakthi Kumar Seeni Raj [Syncfusion]
Replied On July 10, 2019 08:44 AM UTC

Hi Javier,  

Thanks for the update.  

We are glad to hear that your requirement has been achieved and you are good to go. Please get back to us, if you require further assistance on this. 

Regards,  
Seeni Sakthi Kumar S. 


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Please sign in to access our forum

This page will automatically be redirected to the sign-in page in 10 seconds.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon