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.
To make the task easier for you I have reproduced the problem in the attached example.
Hi Ajith,
take a look at the example I attached to you in the previous message, it perfectly reproduces the situation.
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:Update:
After update:
Hi,
are news?
|
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>
|
Hi Ajith,
thanks for support.
Perfect, now it works.