update grid not refresh detailtemplate

Hi,

I have this View:

@using System.Globalization;

@using BloomApp_WEB.Models.ViewModels;

@model IEnumerable<ProdottiVM>


@{

    Layout = "~/Views/Shared/_Master.cshtml";

    ViewBag.TitoloPagina = BloomApp_WEB.Resources.Prodotti.TitoloPagina;

    ViewBag.Titolo = BloomApp_WEB.Resources.Prodotti.Titolo;


}


<div class="row">

    @Html.EJS().Dialog("ErrorList").Header(BloomApp_WEB.Resources.Common.DefaultDialogTitolo).IsModal(true).ShowCloseIcon(true).Width("30%").Visible(false).Render()

</div>

<div class="card shadow mb-4">

    <div class="card-body">

        @Html.AntiForgeryToken()

        @(Html.EJS().Grid<ProdottiVM>("GridProdotti").DataSource(dataManager => { dataManager.Json(((IEnumerable<ProdottiVM>)Model).ToArray()).InsertUrl("InsProdotti").UpdateUrl("UpdProdotti").RemoveUrl("DelProdotti").Adaptor("RemoteSaveAdaptor"); }).DetailTemplate("#detailtemplate").Load("load").ActionBegin("actionBegin").ActionComplete("actionComplete").ActionFailure("gridFailure").Columns(col =>

    {

        col.Field("IdProdotto").IsPrimaryKey(true).Visible(false).Add();

        col.Field("Nome").AutoFit(true).Add();

        col.Field("PrezzoBase").AutoFit(true).Format("C2").Add();

        col.Field("VisibileCatalogo").AutoFit(true).DisplayAsCheckBox(true).Add();

        col.Field("Offerta").AutoFit(true).DisplayAsCheckBox(true).Add();


    }).AllowPaging().PageSettings(page => page.PageSizes(true)).AllowSorting().EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).ShowDeleteConfirmDialog(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog).Template("#dialogtemplate");}).Toolbar(new List<string>() { "Add","Edit","Delete", "Print", "Search" }).Render())

    </div>

</div>

@section scripts{

    <script type="text/x-template" id="detailtemplate">

        <table class="detailtable" width="50%">

            <tbody>

                <tr>

                    <td rowspan="8" style="text-align:center;">

                        ${if (!PathFoto)}

                        <img class='img-thumbnail' src="@Url.Content("~/Content/images/Polaroid.png")" alt="Foto" />

                        ${else}

                        <img class='img-thumbnail' src="@Url.Content("${PathFoto}")" alt="Foto" />

                        ${/if}

                    </td>

                </tr>

                <tr>

                    <td>

                        ${if (!Descrizione)}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Descrizione: </span> -

                        ${else}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Descrizione: </span> ${Descrizione}

                        ${/if}

                    </td>

                </tr>

                <tr>

                    <td>

                        ${if (!QuantitaCarrello)}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.QuantitàCarrello: </span> -

                        ${else}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.QuantitàCarrello: </span> ${QuantitaCarrello}

                        ${/if}

                    </td>

                    <td>

                        ${if (!QuantitaPianale)}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.QuantitàPianale: </span> -

                        ${else}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.QuantitàPianale: </span> ${QuantitaPianale}

                        ${/if}

                    </td>

                </tr>

                <tr>

                    <td>

                        ${if (!Categoria)}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Categoria: </span> -

                        ${else}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Categoria: </span> ${Categoria.Nome}

                        ${/if}

                    </td>

                    <td>

                        ${if (Listini.length == 0)}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Listini: </span> -

                        ${else}

                        <span class="text-gray-800">@BloomApp_WEB.Resources.Prodotti.Listini: </span>

                        ${for (Listino of Listini)}

                        - ${Listino.Nome}

                        ${/for}

                        ${/if}

                    </td>

                </tr>

            </tbody>

        </table>

    </script>


    <script type="text/javascript">

        loadCultureFiles('@CultureInfo.CurrentCulture.TwoLetterISOLanguageName');


        function load(args) {

        // this.dataSource.adaptor = socAdaptor;

        };


        function onFileUpload(args) {

            args.customFormData = [{ 'currentFoto': document.getElementById("Foto").src }];

        }


        function onFileRemove(args) {

            args.customFormData = [{ 'currentFoto': document.getElementById("Foto").src }];

        }


        function onFileSuccess(args) {

            var headers = args.response.headers;

            header = headers.split("imgfoto: ");

            header = header[1].split("\r")

            filename = header[0].split(/(\\|\/)/g).pop();

            filepath = location.origin + location.pathname + '/../../../Content/images/Prodotti/' + filename;

            document.getElementById("Foto").src = filepath;

            document.getElementById("pthFoto").value = "~/Content/images/Prodotti/" + filename;

        }


        function actionBegin(args) {

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

                var listInstance = args.form.querySelector("#IdListini").ej2_instances[0];

                var itemValues = "";

                listInstance.getSelectedItems().forEach(ele => {

                    if (itemValues === "")

                        itemValues = ele.dataset.value;

                    else

                        itemValues = itemValues + ", " + ele.dataset.value;

                });

                args.data["IdListini"] = itemValues;

            }

        }


             function actionComplete(args) {

            if (args.requestType === 'beginEdit' || args.requestType === 'add') {

                let spinner = ej.popups.createSpinner({ target: args.dialog.element });

                ej.popups.showSpinner(args.dialog.element);

                if (args.requestType === 'beginEdit') {

                     var dialog = args.dialog;

                    dialog.header = '@BloomApp_WEB.Resources.Common.Modifica ' + args.rowData['Nome'];

                    args.form.ej2_instances[0].addRules('Nome', { required: true });

                    args.form.ej2_instances[0].addRules('PrezzoBase', { required: true });

                    args.form.ej2_instances[0].refresh();

                    var ajax = new ej.base.Ajax({

                        url: "@Url.Action("EditpartialProdotti", "Company")", //render the partial view

                        type: "POST",

                        contentType: "application/json",

                        data: JSON.stringify({ value: args.rowData })

                    });

                    ajax.send().then(function (data) {

                        appendElement(data, args.form); //render the edit form with selected record

                        args.form.elements.namedItem('Nome').focus();

                        ej.popups.hideSpinner(args.dialog.element);

                    }).catch(function (xhr) {

                        console.log(xhr);

                        ej.popups.hideSpinner(args.dialog.element);

                    });

                }

                if (args.requestType === 'add') {

                    var dialog = args.dialog;

                    dialog.header = '@BloomApp_WEB.Resources.Common.NuovoRecord ';

                    args.form.ej2_instances[0].addRules('Nome', { required: true });

                    args.form.ej2_instances[0].addRules('PrezzoBase', { required: true });

                    args.form.ej2_instances[0].refresh();

                    var ajax = new ej.base.Ajax({

                        url: "@Url.Action("AddpartialProdotti", "Company")", //render the partial view

                        type: "POST",

                        contentType: "application/json",

                        data: JSON.stringify({ value: args.rowData })

                    });

                    ajax.send().then(function (data) {

                        appendElement(data, args.form); //Render the edit form with selected record

                        args.form.elements.namedItem('Nome').focus();

                        ej.popups.hideSpinner(args.dialog.element);

                    }).catch(function (xhr) {

                        console.log(xhr);

                        ej.popups.hideSpinner(args.dialog.element);

                    });

                }

             }

        };


        function appendElement(elementString, form) {

            form.querySelector("#dialogTemp").innerHTML = elementString;

              // refresh method of the formObj

            var script = document.createElement('script');

            script.type = "text/javascript";

            var serverScript = form.querySelector("#dialogTemp").querySelector('script');

            script.textContent = serverScript.innerHTML;

            document.head.appendChild(script);

            serverScript.remove();

        };


    </script>


    <script id='dialogtemplate' type="text/x-template">

        <div id="dialogTemp">

        </div>

    </script>


}

This controller:

 [HttpPost]

        //[ValidateAntiForgeryToken]

        [Authorize(Roles = "Azienda Produttrice")]

        public async Task<ActionResult> UpdProdotti(ProdottiVM value)/*CRUDModel<ProdottiVM> requestData)*/

        {

            //ProdottiVM value = new ProdottiVM();

            log4net.Config.XmlConfigurator.Configure();

            log.Info("Inizio esecuzione UpdProdotti(ProdottiVM value, string action)");

            try

            {

                using (_prodottoRepository)

                using (_prodottoListinoRepository)

                {

                    //value = ConvertToModel(requestData);

                    Prodotto prodotto = await _prodottoRepository.GetProdotto(value.IdProdotto);

                    if (ModelState.IsValid)

                    {

                        prodotto.DataCreazione = DateTime.Now.Date;

                        prodotto.Deleted = value.Deleted;

                        prodotto.Descrizione = value.Descrizione;

                        prodotto.IdCategoria = value.IdCategoria;

                        prodotto.IdProdotto = value.IdProdotto;

                        prodotto.Nome = value.Nome;

                        prodotto.Offerta = value.Offerta;

                        prodotto.PathFoto = value.PathFoto;

                        prodotto.PrezzoBase = value.PrezzoBase;

                        prodotto.QuantitàCarrello = value.QuantitaCarrello;

                        prodotto.QuantitàPianale = value.QuantitaPianale;

                        prodotto.VisibileCatalogo = value.VisibileCatalogo;


                        if (await _prodottoRepository.UpdProdotto(prodotto) != 1)

                        {

                            Response.StatusCode = 422;

                        }

                        else

                        {

                            foreach (Guid IdListino in value.IdListini)

                            {

                                ProdottoListino pl = new ProdottoListino

                                {

                                    IdListino = IdListino,

                                    IdRelazione = Guid.NewGuid(),

                                    IdProdotto = value.IdProdotto

                                };


                                if (!await _prodottoListinoRepository.Exist(pl.IdProdotto, pl.IdListino))

                                {

                                    await _prodottoListinoRepository.InsProdottoListino(pl);

                                }


                            }


                            foreach (ProdottoListino plDB in await _prodottoListinoRepository.GetProdottoListinoByProdotto(value.IdProdotto))

                            {

                                if (!value.IdListini.Contains(plDB.IdListino))

                                {

                                    await _prodottoListinoRepository.DelProdottoListino(plDB.IdRelazione);

                                }

                            }

                            value = await LoadProdotto(prodotto.IdProdotto);

                        }

                    }

                    else

                    {

                        var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));

                        Response.StatusCode = 422;

                        throw new Exception(Server.HtmlEncode(message));

                    }

                    log.Info("Fine esecuzione UpdProdotti(CRUDModel<ProdottiVM> requestData)");

                }

            }

            catch (Exception ex)

            {

                var message = ex.InnerException == null ? ex.Message : ex.InnerException.Message;

                log.Error(string.Format("Errore:{0}", message.ToString()));

                Response.StatusCode = Response.StatusCode == 200 ? 500 : Response.StatusCode;

                Errori.CustomMessage = Response.StatusCode == 500 ? $"/{Resources.Error.TestoP500}" : message;

                throw new Exception(Server.HtmlEncode(Errori.CustomMessage));

            }

            return Json(value);

        }

The problem is that when I update a grid row, the grid updates but the detail does not, even if the Viewmodel contains all the necessary fields.

If I reload the page, the detail also displays updates.

All data, both in the grid and in the detail, are stored in a single table.

 





9 Replies

PL Pio Luca Valvona July 29, 2021 08:39 PM UTC

To make the task easier for you I have reproduced the problem in the attached example.


Attachment: GridUpdated861021168_75641676.zip


AG Ajith Govarthan Syncfusion Team July 30, 2021 02:57 AM UTC

Hi Pio Luca Valvona, 

Thanks for contacting Syncfusion support. 

Query: update grid not refresh detailtemplate 
 
Based on your query you are facing issue update issue with detail template in your Grid application. So, before we proceed to your query, please share below details to validate further on your requirement. 

  1. Please share the screenshot or video demonstration of the reported issue?
 
  1. Have you updated the detailTemplate related data with Grid dialog template editing?

  1. Please let us know that how you are updating the detail template values?
 
  1. Please let us know if you are facing any script error in the console.

  1. Share the Syncfusion package version.
 
Regards, 
Ajith G. 



PL Pio Luca Valvona July 30, 2021 06:48 AM UTC

Hi Ajith,

take a look at the example I attached to you in the previous message, it perfectly reproduces the situation.



AG Ajith Govarthan Syncfusion Team August 3, 2021 03:43 AM UTC

Hi Pio Luca Valvona, 

Sorry for the convenience caused. 

Query: The problem is that when I update a grid row, the grid updates but the detail does not, even if the Viewmodel contains all the necessary fields.If I reload the page, the detail also displays updates. 
 
We have checked the attached the attached sample and found that you have not handled the update method at the server side and also, we found that the detail template data refreshes properly when update the data in your Grid application. So, to know about your exact issue, please share the video demonstration of the reported issue to provide you the prompt solution at the earliest. 

Regards, 
Ajith G. 



PL Pio Luca Valvona August 3, 2021 06:43 AM UTC

Hi Ajith,

As I told you in the attached example the problem occurs, I prove it to you with the images that I attach to you.

Before Update:before.pngUpdate:

update.png

After update:

after.png



PL Pio Luca Valvona August 6, 2021 08:34 AM UTC

Hi,

are news?



AG Ajith Govarthan Syncfusion Team August 6, 2021 04:00 PM UTC

Hi Pio Luca, 

Thanks for the update. 
 
Query: As I told you in the attached example the problem occurs, I prove it to you with the images that I attach to you. 
 
We have checked your attached sample and able to reproduce the reported behavior at our end. By default, in our EJ2 Grid, when you update the row, we will refresh the content of the respective row only and we won’t refresh the detail template when you update the data in the Grid component, which is the default behavior of our EJ2 Grid. 

 So, to update the data in the detail template when you update the data in the Grid component, we suggest you call the refresh method of the Grid component. For your convenience we have attached the sample, please refer them for your reference. 

Code Example: 

Index.cshtml 

<div class="control-section"> 
@Html.EJS().Grid("DefaultPaging").DataBound("dataBound").DetailTemplate("#detailtemplate").DataSource(ds => ds.Json(ViewBag.datasource).Adaptor("RemoteSaveAdaptor").InsertUrl("/Home/Insert").RemoveUrl("/Home/Remove") 
.UpdateUrl("/Home/Update")).ActionComplete("actionComplete").ActionBegin("actionBegin").Columns(col => 
{ 
 
col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(); 
col.Field("CustomerID").HeaderText("Customer ID").Width("150").Add(); 
col.Field("EmployeeID").ForeignKeyField("EmployeeID").ForeignKeyValue("FirstName") 
.DataSource((IEnumerable<object>)ViewBag.ddData).HeaderText("Name").Width("120").Add(); 
col.Field("OrderDate").HeaderText("Order Date").EditType("datepickeredit").Format("yMd").Width("170").Type("date").Add(); 
col.Field("City").HeaderText("City").EditType("dropdownedit").Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(); 
 
}).Height("400").AllowPaging().Toolbar(new List<string> 
() { "Add", "Edit", "Delete", "Update", "Cancel" }).EditSettings(edit => { edit.AllowEditing(true).AllowAdding(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog).Template("#dialogtemplate"); }).Render() 
</div> 
<script type="text/x-template" id="detailtemplate"> 
<table class="detailtable" width="50%"> 
<tbody> 
<tr> 
<td> 
${if (!CustomerID)} 
<span class="text-gray-800">t: </span> - 
${else} 
<span class="text-gray-800">t: </span> ${CustomerID} 
${/if} 
</td> 
</tr> 
</tbody> 
</table> 
</script> 
 
<script> 
 
 
 
 
var strm; 
 
var btnChanged; 
var btnChecked; 
function actionBegin(args) { 
 
} 
 
function dataBound(args) { 
} 
 
function actionComplete(args) { 
if (args.requestType === 'beginEdit') { 
args.dialog.header = 'Edit Dialog'; 
args.dialog.height = '400px'; 
var ajax = new ej.base.Ajax({ 
url: "/Home/editpartial", //render the partial view 
type: "POST", 
contentType: "application/json", 
data: JSON.stringify({ value: args.rowData }) 
}); 
ajax.send().then(function (data) { 
$("#dialogTemp").html(data); //Render the edit form with selected record 
}).catch(function (xhr) { 
console.log(xhr); 
}); 
} 
if (args.requestType === 'add') { 
args.dialog.header = 'Add Dialog'; 
var ajax = new ej.base.Ajax({ 
url: "/Home/AddPartial", //render the partial view 
type: "POST", 
contentType: "application/json", 
}); 
ajax.send().then(function (data) { 
$("#dialogTemp").html(data); //Render the edit form with selected record 
}).catch(function (xhr) { 
console.log(xhr); 
}); 
} 
if (args.requestType === "save") { 
var grid = document.getElementsByClassName("e-grid")[0].ej2_instances[0]; 
grid.refresh() 
} 
 
} 
</script> 
 
<script id='dialogtemplate' type="text/x-template"> 
<div id="dialogTemp"> 
</div> 
</script> 

 


Note: in your attached sample we found that you have not handled the CRUD actions properly in your Grid application. So, we have handled the CRUD actions properly in the above sample. 

Please get back to us if you need further assistance. 

Regards, 
Ajith G. 



PL Pio Luca Valvona August 6, 2021 04:35 PM UTC

Hi Ajith,

thanks for support.

Perfect, now it works.



AG Ajith Govarthan Syncfusion Team August 9, 2021 12:53 PM UTC

Hi Pio Luca, 

Thanks for the update. 

Query: Perfect, now it works. 
 
We are happy to hear that the provided solution resolved your reported issue. 

Please get back to us if you need further assistance. 

Regards, 
Ajith G. 


Loader.
Up arrow icon