Insert with Dialog Template

Hi, 
I am having problems when inserting a record through a dialog template. After saving to the database, the dialog remains locked at load time and the console returns this error: Unable to get property 'trim' of undefined or null reference.
I think the problem is the dropdown in the template, since removing works.
I have same issue on the two templates of the detail grids, in which there is a dropdown.
About detail grid, I not perform insert, because save button not redirect to inserturl, and action in controller not fire.

View: see attached file

Controller:

[Authorize(Roles = ("Administrator"))]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> InsClienti(ClientiVM value)
        {
 
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Inizio esecuzione InsClienti(ClientiVM value)");
            List<ClientiVM> model = new List<ClientiVM>();
            try
            {
                ModelState.Remove("value.IDUtente");
                if (ModelState.IsValid)
                {
                    Utente cliente = new Utente()
                    {
                        CF = value.CF,
                        Codice = value.Codice,
                        Cognome = value.Cognome,
                        Deleted = value.Deleted,
                        Email = value.Email,
                        EmailRegistrazione = value.EmailRegistrazione,
                        EmailRegistrazioneInviata = value.EmailRegistrazioneInviata,
                        IDRuolo = value.IDRuolo,
                        IDUtente = Guid.NewGuid(),
                        Indirizzo = value.Indirizzo,
                        Nome = value.Nome,
                        Password = Crypto.HashPassword(value.Password),
                        PIVA = value.PIVA,
                        RagioneSociale = value.RagioneSociale,
                        Referente = value.Referente,
                        Telefono = value.Telefono
                    };
                    if (await _utenteRepository.Exist(cliente))
                    {
                        HttpContext.Response.AddHeader("Exception", Resources.Utenti.UtenteGiaPresente);
                        Response.StatusCode = 412;
                    }
                    else
                    {
                        if (await _utenteRepository.InsUtente(cliente) != 1)
                        {
                            HttpContext.Response.AddHeader("Exception", Resources.Common.ErroreTrasmissione);
                            Response.StatusCode = 412;
                        }
                        else
                        {
                            if (cliente.EmailRegistrazione)
                            {
                                SendEmailNewCustomer(cliente);
                                cliente.EmailRegistrazioneInviata = true;
                                await _utenteRepository.UpdUtente(cliente);
                            }
                        }
                    }
                    model = await LoadClienti();
                }
                else
                {
                    var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                    HttpContext.Response.AddHeader("Exception", Server.HtmlEncode(message));
                    Response.StatusCode = 412;
                }
 
                log.Info("Fine esecuzione InsClienti(ClientiVM value)");
            }
            catch (Exception ex)
            {
 
                log.Error(string.Format("Errore:{0}", ex.InnerException == null ? ex.Message : ex.InnerException.Message));
                throw ex;
            }
            return Json(model, JsonRequestBehavior.AllowGet);
        }

Attachment: View_752f1dab.7z

9 Replies

PL Pio Luca Valvona January 5, 2018 11:32 AM UTC

Unfortunately the error also occurs on another view with a simple grid without a dropdown: SCRIPT5007: Unable to get property 'trim' of undefined or null reference

@(Html.EJ().Grid<ServiziVM>("ResultGrid").Datasource(ds => ds.Json(Model).InsertURL(Url.Action("InsServizi""Servizi")).RemoveURL(Url.Action("DelServizi","Servizi")).UpdateURL(Url.Action("UpdServizi","Servizi")).Adaptor(AdaptorType.RemoteSaveAdaptor))
                                                                                            .Columns(col =>
                                                                                            {
                                                                                                col.Field("IDServizio").Visible(false).IsPrimaryKey(true).Add();
                                                                                                col.Field("NomeServizio").Add();
                                                                                                col.Field("DescrizioneServizio").Add();
                                                                                                col.Field("Deleted").DisplayAsCheckbox().Add();
                                                                                            })
                                                                                            .Locale(CultureInfo.CurrentCulture.TextInfo.CultureName).IsResponsive(true).EnableResponsiveRow(true).AllowPaging().AllowSorting().AllowFiltering()
                                                                                            .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.DialogTemplate).DialogEditorTemplateID("#ServiziTemplate"); })
                                                                                            .ToolbarSettings(tb => tb.ShowToolbar().ToolbarItems(tbi =>
                                                                                            {
                                                                                                tbi.AddTool(ToolBarItems.Add);
                                                                                                tbi.AddTool(ToolBarItems.Delete);
                                                                                                tbi.AddTool(ToolBarItems.ExcelExport);
                                                                                                tbi.AddTool(ToolBarItems.PdfExport);
                                                                                                tbi.AddTool(ToolBarItems.PrintGrid);
                                                                                            })).Mappers(m => m.ExportToExcelAction(Url.Action("ExportServiziExcel")).ExportToPdfAction(Url.Action("ExportServiziPDF"))).ClientSideEvents(eve => eve.Load("Load").ActionComplete("Complete").ActionFailure("Failure")))


<script type="text/template" id="ServiziTemplate">
       @Html.AntiForgeryToken()
       <input type="hidden" name="IDServizio" value="{{: IDServizio}}" />
       <table cellspacing="10" class="griddialog">
           <tr>
               <td style="text-alignright;">
                   <label>@PLV.Web.Resources.Servizi.NomeServiziolabel>
               td>
               <td style="text-alignleft">
                   <input name="NomeServizio" value="{{: NomeServizio}}" class="input-lg" />
               td>
           tr>
           <tr>
               <td style="text-alignright;">
                   <label>@PLV.Web.Resources.Servizi.DescrizioneServiziolabel>
               td>
               <td style="text-alignleft">
                   <input name="DescrizioneServizio" value="{{: DescrizioneServizio}}" class="input-lg" />
               td>
           tr>
           <tr>
               <td style="text-alignright;">
                   <label>@PLV.Web.Resources.Servizi.Eliminatolabel>
               td>
               <td style="text-alignleft">
                   <input type="checkbox" name="Deleted" class="input-lg" value="{{:Deleted}}" />
               td>
           tr>
       table>
       <hr />
   script>


function Failure(args) {
           var str = "";
           str = args.error.getResponseHeader('Exception');
           $('#ErrorList').html("");
           $('#ErrorList').html("

+ str + "

"
);            $('#ErrorList').ejDialog("open");            $("#" + this._id + "_dialogEdit").ejDialog("close");            this.element.ejWaitingPopup("hide");        }         function Complete(args) {            if (args.requestType == "beginedit" || args.requestType == "add") {                if (args.requestType == "beginedit") {                    $("#" + this._id + "_dialogEdit").ejDialog("option""title""@PLV.Web.Resources.Clienti.DialogModificaCliente")                }                if (args.requestType == "add") {                    $("#" + this._id + "_dialogEdit").ejDialog("option""title""@PLV.Web.Resources.Clienti.DialogNuovoCliente")                }            }        };








RS Renjith Singh Rajendran Syncfusion Team January 5, 2018 01:06 PM UTC

Hi Pio, 

Thanks for contacting Syncfusion support. 

We have analyzed your query and code examples. We are not able to reproduce the reported issue. We have prepared a sample based on your requirement in version 15.4.0.20(latest Syncfusion version), which could be downloaded from the link below, 

If you are still facing the issue, please get back to us with the following details, 
 
  1. Share the stack trace of the script error you are facing.
  2. Share the screen shot or video demonstration of the issue.
  3. Share exact scenario or proper replication procedure.
  4. Essential Studio version and browser details.
  5. If possible share a simple sample to reproduce the issue or reproduce the issue in the attached sample.

Regards, 
Renjith Singh Rajendran. 



PL Pio Luca Valvona January 5, 2018 01:38 PM UTC

Thank you, for support.
Almost with certainty I found that the problem is in the "LOAD" of the grid, then in the code for the AntiforgeryToken, because if I delete the event the insert works, obviously without passing the token.
How can I fix?


RS Renjith Singh Rajendran Syncfusion Team January 8, 2018 12:47 PM UTC

Hi Pio, 

We have logged it as an issue “Script error thrown during insert when column with string value set as primary key”. The fix for this issue will be included in the Volume 1,2018 release which is scheduled to be rolled out in the mid of February. 

We could see that in the dialog template you have hidden the primary key input element. With string values as primary key and not updating the string primary column value during insert then the script error will occur. We suggest you to use the workaround, set the value for the string typed primary key column as “ ” during insert by using the ActionBegin event of Grid. Please refer the code example below, 

[Index.cshtml] 
 
@(Html.EJ().Grid<object>("FlatGrid") 
        ... 
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(90).Add(); 
            ... 
            ... 
       }) 
       .ClientSideEvents(eve => eve.ActionComplete("complete").ActionBegin("begin") ) 
        ) 
 
<script type="text/javascript"> 
    function begin(args) { 
        if (document.getElementsByClassName("e-addedrow").length && args.requestType == "save") 
        { 
            args.rowData.OrderID = ""; 
        } 
    } 
<script> 

Please refer the documentation link below, 

Please get back to us if you need further assistance. 

Regards, 
Renjith Singh Rajendran. 



PL Pio Luca Valvona January 9, 2018 09:59 PM UTC

Thank you,
this workaround works well on master grid,
but when I use this on detail grid, I see only new row without data also if I return 
return Json(value, JsonRequestBehavior.AllowGet);
Also if I try to update a newly entered record, the ID is null.

Regards,
Pio Luca Valvona


RS Renjith Singh Rajendran Syncfusion Team January 10, 2018 01:33 PM UTC

Hi Pio, 

We have analyzed your query. The details of a MasterGrid is shown in the DetailGrid based on a foreign key column which you have mapped to detail grid. So if a new record is added to a DetailGrid then the foreign key column of the DetailGrid should also be updated the same value as the MasterGrid foreign key column. If the DetailGrid foreign key column has different value other than the MasterGrid foreign key column. Then the DetailGrid won’t be populated and it remains empty. 

So we suggest you to ensure whether you have provided the foreign key column value of DetailGrid same as the value of MasterGrid foreign key column. 

If you are still facing the issue please share with us code samples of how you have rendered the detail grid both (View and Controller) codes. 

Regards, 
Renjith Singh Rajendran. 



PL Pio Luca Valvona January 10, 2018 02:32 PM UTC

Hi Renjith,
thank you for support.

ID is null also when open dialog for update a newly entered record in master grid.
This situation is started when I used a custom adptor:

var dmAdaptorUpdate = function (keyField, value, tableName) {
           var res = this.adaptor.update(this, keyField, value, tableName);
           return $.ajax($.extend({
               beforeSend: ej.proxy(this._beforeSend, this)
           }, res));
       }
 
       var dmAdaptorInsert = function (data, tableName) {
           var res = this.adaptor.insert(this, data, tableName);
           var deffer = $.Deferred();
           $.ajax($.extend({
               beforeSend: ej.proxy(this._beforeSend, this),
               success: ej.proxy(function (record, status, xhr, request) {
                   record = function () {
                       if (data.d)
                           data = data.d;
                       return data;
                   };
                   deffer.resolveWith(this, [{ record: record, dataManager: this }]);
               }, this),
               error: function (e) {
                   deffer.rejectWith(this, [{ error: e, dataManager: this }]);
               }
           }, res));
 
           return deffer.promise();
       }
 
       var adaptor = new ej.remoteSaveAdaptor().extend({
           update: function (dm, keyField, value, tableName) {
               var token = value.__RequestVerificationToken;
               delete value['__RequestVerificationToken'];
               return {
                   type: "POST",
                   url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url,
                   data: {
                       __RequestVerificationToken: token,
                       value: value,
                       action:"update"
                   }
               };
           },
           insert: function (dm, data, tableName) {
               var token = data.__RequestVerificationToken;
               delete data['__RequestVerificationToken'];
               return {
                   type: "POST",
                   url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url,
                   data: {
                       __RequestVerificationToken: token,
                       value: data,
                       action:"insert"
                   }
               };
           },
       })
 
       function Load(args) {
           this.model.dataSource.adaptor = new adaptor();
           this.model.dataSource.update = dmAdaptorUpdate;
           this.model.dataSource.insert = dmAdaptorInsert;
       };
If I use a default remoteSaveAdaptor without Antiforgery all works well.
Although the object has all fields complete, it seems that the grid does not come all the fields that are not strings..

Regard


RS Renjith Singh Rajendran Syncfusion Team January 11, 2018 05:29 PM UTC

Hi Pio, 

We have analyzed the code samples provided. We are not able to reproduce the reported issue. We have prepared a sample based on your requirement with the AntiForgeryToken in which the CRUD operations in both detail and master Grid works fine. Please download the sample from the link below, 


If you are still facing the issue, please get back to us with a simple issue reproducing sample, or reproduce the issue in the attached sample. 

Regards, 
Renjith Singh Rajendran. 



RS Renjith Singh Rajendran Syncfusion Team January 30, 2018 12:05 PM UTC

Hi Pio, 

We are sorry for the inconvenience caused.  

As we further analyzed the sample from the code snippets you shared, we found that it is a sample side issue. We have prepared a modified sample based on your requirement. Please download it from the link below, 

Since you are not updating the primaryKey column value during inserting record, we suggest you to use the “isIdentity” property of Grid. We need to handle isIdentity column on the serverside while updating records to the database. In the below code example, we have set the value to “isIdentity” column as “” . Refer to the code example. 

[GridFeatures.cshtml] 
 
col.Field("CustomerID").HeaderText("Customer ID").IsPrimaryKey(true).IsIdentity(true).Width(90).Add(); 
 
[GridController.cs] 
 
public ActionResult Insert(EditableOrder value) 
        { 
            value.CustomerID = ""; 
            OrderRepository.Add(value); 
           return Json(value, JsonRequestBehavior.AllowGet);  
        } 

And also in the custom adaptor, you should not return function from Insert metjod. Since the record parameter has the updated data from server side, you need to return the data to Grid. 

<script type="text/javascript"> 
    ... 
   var dmAdaptorInsert = function (data, tableName) { 
        var res = this.adaptor.insert(this, data, tableName); 
        ... 
           success: ej.proxy(function (record, status, xhr, request) { 
                recordFn = function () { 
                    if (record.d) 
                        record = record.d; 
                    return record; 
                }; 
                deffer.resolveWith(this, [{ record: recordFn(), dataManager: this }]); 
            }, this), 
            ... 
       }, res)); 
 
        return deffer.promise(); 
    } 
    ... 
</script> 


Please get back to us if you need further assistance. 

Regards, 
Renjith Singh Rajendran. 


Loader.
Up arrow icon