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

Dialog Template Not Work In Net Core 3.0

I tried the solution from this thread (https://www.syncfusion.com/forums/141281/implement-dialog-template-under-grid-ejs-grid), but it didn't work. When I click on the Add or Edit button in dialog template.

What am I missing? (I'm using ASP.NET Core 3 EJ2, Views and Controllers, Razor pages, Entity Framework and sql server).


Index

<div>

    <h2> CARGOS</h2>

    <h6> DESCRIPCIÓN </h6>

 

    <ejs-grid id="Grid" locale="es" gridLines="Both" actionFailure="actionFailure" dataBound="dataBound" rowSelected="rowSelected" allowPaging="true" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Search"})" actionComplete="actionComplete">

        <e-data-manager url="/Cargos/UrlDataSource" adaptor="UrlAdaptor" insertUrl="/Cargos/Insert" updateUrl="/Cargos/Update" removeUrl="/Cargos/Delete"></e-data-manager>

        <e-grid-searchsettings fields="@(new string[] { "Codigo","Nombre"})"></e-grid-searchsettings>

        <e-grid-editSettings allowAdding="true" allowEditing="true" allowDeleting="true" showDeleteConfirmDialog="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings>

        <e-grid-pagesettings pageCount="5 "></e-grid-pagesettings>

        <e-grid-columns>

            <e-grid-column field="id" isPrimaryKey="true" visible="false"></e-grid-column>

            <e-grid-column field="codigo" headerText="Código" validationRules="@(new { required=true})" width="20"></e-grid-column>

            <e-grid-column field="nombre" headerText="Nombre" validationRules="@(new { required=true})" width="80"></e-grid-column>

            <e-grid-column field="basico" headerText="Básico" validationRules="@(new { required=true})" width="40" textAlign="Right" editType="numericedit" format="N2"></e-grid-column>

        </e-grid-columns>

    </ejs-grid>

 

</div>

 

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

    <div id="dialogTemp">

    </div>

</script>

….

 

function actionComplete(args) {

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

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

                    // Called the partial view elements

                    var ajax = new ej.base.Ajax({

                        url: "@Url.Action("EditPartial", "Cargos")", //render the Edit 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 in newly created template with the selected record

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

                    }).catch(function (xhr) {

                        console.log(xhr);

                    });

                }

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

                    var ajax = new ej.base.Ajax({

                        url: "@Url.Action("AddPartial","Cargos")", //render the Add 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('Codigo').focus();

                    }).catch(function (xhr) {

                        console.log(xhr);

                    });

                }

         }

    }

 

 


    function appendElement(elementString, form) {

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

        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();

    }


Controller

Controler

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using System.Collections;

using NominaNetCore1.Models;

using Syncfusion.EJ2.Base;

using Microsoft.EntityFrameworkCore;

 

namespace NominaNetCore1.Controllers

{

    public class CargosController : Controller

    {

        private readonly NominaNetCore1Context _context;

        public CargosController(NominaNetCore1Context context)

        {

            _context = context;

        }


        public IActionResult Insert([FromBody]CRUDModel<CargoSet> param)

        {

 

            var obj = _context.CargoSet.Where(o => o.Codigo == param.Value.Codigo).SingleOrDefault();

            if (obj != null) //Check already exisiting

            {

                throw new InvalidOperationException("Código de Cargo ya existe");//Exception thrown if exisiting    

            }

 

            // Usuario Adiciona

            param.Value.Created = DateTime.Now;

 

            _context.Add(param.Value);

            _context.SaveChanges();

 

            return Json(param.Value);

        }

 

        public IActionResult Update([FromBody]CRUDModel<CargoSet> param) // Update record

        {

            CargoSet data = _context.CargoSet.Single(o => o.Id == int.Parse(param.Key.ToString()));

 

            // Usuario Modifica

            param.Value.Modified = DateTime.Now;

 

            _context.Entry(data).CurrentValues.SetValues(param.Value);

            _context.Entry(data).State = EntityState.Modified;

            _context.SaveChanges();

 

            return Json(param.Value);

        }

 

        public IActionResult Delete([FromBody]CRUDModel<CargoSet> param) // Delete record

        {

            CargoSet data = _context.CargoSet.Where(o => o.Id == int.Parse(param.Key.ToString())).FirstOrDefault();

 

            // Usuario Borra

            data.Modified = DateTime.Now;

 

            _context.CargoSet.Remove(data);

            _context.SaveChanges();

            return Json(data);

        }

 

        public IActionResult EditPartial([FromBody] CRUDModel<CargoSet> param)

        {

            return PartialView("_DialogEditPartial", param.Value);

        }

 

        public IActionResult AddPartial([FromBody] CRUDModel<CargoSet> param)

        {

            return PartialView("_DialogAddPartial");

        }

    }

}




What am I missing?












Attachment: Dialog_Template_Not_Work_In_Net_Core_3_d84dfdbb.rar

11 Replies

SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team December 4, 2019 11:47 AM UTC

Hi Luis, 

Thanks for contacting us. 

We have checked the code example and screenshots that you have provided. We could see that you have not defined template for primary key column in both edit and add partial views. While editing the it is necessary to include primary key values while editing 

Please find the below documentation link for more information. 


Please share the video demonstration of the issue, and explain the issue you are facing, (like script error or updated data is not reflecting in Grid).  

Please find the below code example and  the below screenshots to ensure the primary key values are passed to server side properly. 

Index 
<ejs-grid id="Grid" allowPaging="true" toolbar="@(new List<string>() {"Add", "Edit", "Update", "Delete" })" actionComplete="actionComplete"> 
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings> 
    <e-data-manager url="/Home/UrlDataSource" adaptor="UrlAdaptor" insertUrl="/Home/Insert" updateUrl="/Home/Update" removeUrl="/Home/Remove"></e-data-manager> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" visible="false" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
. . . 
</ejs-grid> 
Addpartial 
<div> 
    <div class="form-row"> 
        <div class="form-group col-md-6"> 
            <div class="e-float-input e-control-wrapper"> 
                <input asp-for="OrderID" type='text' /> 
                <span class="e-float-line"></span> 
                <label asp-for="OrderID" class="e-float-text e-label-top">Order ID</label> 
            </div> 
        </div> 
         . . . 
   </div> 
</div> 
 
<ejs-scripts></ejs-scripts> 
EditPartial 
<div> 
    <div class="form-row"> 
        <div class="form-group col-md-6"> 
            <div class="e-float-input e-control-wrapper"> 
                <input asp-for="OrderID" value=@Model.OrderID.ToString() disabled type='text' /> 
                <span class="e-float-line"></span> 
                <label asp-for="OrderID" class="e-float-text e-label-top">Order ID</label> 
            </div> 
        </div> 
         . . . 
</div> 
 
 


Requests in the network tab While editing: 

 

Adding: 

 


Please ensure the above in your sample, if you still faced the issue, please get back to us for further assistance. 

Regards, 
Seeni Sakthi Kumar S 



LU luis December 4, 2019 05:29 PM UTC

I tried the solution..

 

@model NominaNetCore1.Models.CargoSet

@using Syncfusion.EJ2

<div>
    <div class="form-row">
        <div class="form-group col-md-12">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="Id" value=@Model.Id.ToString() disabled type='text' />
                <span class="e-float-line"></span>
                <label asp-for="Id" class="e-float-text e-label-top">Id</label>
            </div>
        </div>
    </div>
    <div class="form-row">
        <div class="form-group col-md-12">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="Codigo" value=@Model.Codigo type='text'/>
                <span class="e-float-line"></span>
                <label asp-for="Codigo" class="e-float-text e-label-top">Código</label>
            </div>
        </div>
    </div>
    <div class="form-row">
        <div class="form-group col-md-12">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="Nombre" value=@Model.Nombre type='text'/>
                <span class="e-float-line"></span>
                <label asp-for="Nombre" class="e-float-text e-label-top">Nombre</label>
            </div>
        </div>
    </div>
    <div class="form-row">
        <div class="form-group col-md-12">
            <div class="e-float-input e-control-wrapper">
                <ejs-numerictextbox id="Basico" value=@Model.Basico format="N2" placeholder="Básico" floatLabelType="Always"></ejs-numerictextbox>
            </div>
        </div>
    </div>
</div>

<ejs-scripts></ejs-scripts>

 

 


but it didn't work. When I click on the Add or Edit button in dialog template.




insertUrl="/Cargos/Insert" updateUrl="/Cargos/Update" related to IActionResult Insert and IActionResult Update Can not be executed.

In mode dialog normal It works perfect

What am I missing?, Please help me.






PS Pavithra Subramaniyam Syncfusion Team December 5, 2019 12:13 PM UTC

Hi luis, 
 
Thanks for your update. 
 
We have tried to replicate the issue at our end. But it is working fine. We are able to add and update the data. Also we are attaching the sample for your reference. 
 
 
It would be helpful to us to validate the issue, if you share the below details, 
 
  1. Share the Syncfusion Nuget(Syncfusion.EJ2.AspNet.Core) version and CDN link version
 
  1. Share if any console error thrown(Since you are mentioning normal and dialog mode it is working fine and cannot access the Insert,
Update methods in dialog template, you might have some script errors in console) 
 
  1. Bind the actionFailure event to Grid and share the stack trace (if any)
 
  1. If you have not any errors in console and actionFailure events , try to reproduce the issue in given sample, are share the issue reproducible sample
 
Regards, 
Pavithra S. 



LU luis December 7, 2019 02:05 AM UTC

 

1.      Share the Syncfusion Nuget(Syncfusion.EJ2.AspNet.Core) version and CDN link version

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>@ViewData["Title"] - NominaNetCore1</title>

    <link rel="stylesheet" rel='nofollow' href="~/lib/bootstrap/dist/css/bootstrap.min.css" />

    <link rel="stylesheet" rel='nofollow' href="~/css/site.css" />

 

    <!-- Syncfusion Essential JS 2 Styles -->

    <link rel="stylesheet" rel='nofollow' href="https://cdn.syncfusion.com/ej2/material.css" />

 

    <!-- Syncfusion Essential JS 2 Scripts -->

    <script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js"></script>

 

</head>

<body>

 

 


 

  1. Cannot access the Insert, Update methods controller in mode dialog template. not show any errors in console or actionFailure events.

 

  1. Trace with http debugger.. When I click on the Add or Edit button in mode dialog template. No fire the Insert, Update methods of controller. 

What am I missing? (I'm using ASP.NET Core 3 EJ2, MVC, Entity Framework Core 3 and sql server database).



SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team December 9, 2019 12:53 PM UTC

Hi luis, 

Thanks for sharing the requested details. 

We have tried to replicate the issue with the mentioned versions. But we were unable to replicate the reported issue at our end. The dialog template is working fine in our end. To validate further about the issue, please do the changes to reproduce the issue in the given sample and revert to us.  


Regards, 
Seeni Sakthi Kumar S


LU luis December 9, 2019 03:43 PM UTC



Thanks, I share the project for you to understand the problem better, it contains your example along with mine.
you example is Home, the mine is cargos.


you example requires the following:

services.AddControllersWithViews().AddNewtonsoftJson(options =>

            {

                // Use the default property (Pascal) casing

                options.SerializerSettings.ContractResolver = new DefaultContractResolver();

            });


This script database Prueba5

USE [Prueba5]
GO
/****** Object:  Table [dbo].[CargoSet]    Script Date: 09/12/2019 10:18:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CargoSet](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [codigo] [nvarchar](10) NULL,
    [nombre] [nvarchar](60) NULL,
    [basico] [decimal](18, 2) NULL,
    [sede] [nvarchar](2) NULL,
    [suscriptor] [nvarchar](255) NULL,
    [CreatedBy] [nvarchar](255) NULL,
    [Created] [datetime] NULL,
    [ModifiedBy] [nvarchar](255) NULL,
    [Modified] [datetime] NULL,
 CONSTRAINT [PK__CargoSet__3214EC07EE871AB6] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[CargoSet] ON
GO
INSERT [dbo].[CargoSet] ([Id], [codigo], [nombre], [basico], [sede], [suscriptor], [CreatedBy], [Created], [ModifiedBy], [Modified]) VALUES (1, N'01', N'PRUEBA1', CAST(828116.00 AS Decimal(18, 2)), N'01', NULL, NULL, NULL, NULL, NULL)
GO
INSERT [dbo].[CargoSet] ([Id], [codigo], [nombre], [basico], [sede], [suscriptor], [CreatedBy], [Created], [ModifiedBy], [Modified]) VALUES (2, N'02', N'PRUEBA2', CAST(828116.00 AS Decimal(18, 2)), N'01', NULL, NULL, NULL, NULL, NULL)
GO
INSERT [dbo].[CargoSet] ([Id], [codigo], [nombre], [basico], [sede], [suscriptor], [CreatedBy], [Created], [ModifiedBy], [Modified]) VALUES (3, N'03', N'PRUEBA3', CAST(828116.00 AS Decimal(18, 2)), N'01', NULL, NULL, NULL, NULL, NULL)
GO
INSERT [dbo].[CargoSet] ([Id], [codigo], [nombre], [basico], [sede], [suscriptor], [CreatedBy], [Created], [ModifiedBy], [Modified]) VALUES (4, N'04', N'PRUEBA4', CAST(828116.00 AS Decimal(18, 2)), N'01', NULL, NULL, NULL, NULL, NULL)
GO
INSERT [dbo].[CargoSet] ([Id], [codigo], [nombre], [basico], [sede], [suscriptor], [CreatedBy], [Created], [ModifiedBy], [Modified]) VALUES (5, N'05', N'PRUEBA5', CAST(828116.00 AS Decimal(18, 2)), N'01', NULL, NULL, NULL, NULL, NULL)
GO
SET IDENTITY_INSERT [dbo].[CargoSet] OFF
GO
ALTER TABLE [dbo].[CargoSet] ADD  CONSTRAINT [DF__CargoSet__codigo__123EB7A3]  DEFAULT ('') FOR [codigo]
GO
ALTER TABLE [dbo].[CargoSet] ADD  CONSTRAINT [DF__CargoSet__nombre__1332DBDC]  DEFAULT ('') FOR [nombre]
GO
ALTER TABLE [dbo].[CargoSet] ADD  CONSTRAINT [DF__CargoSet__basico__14270015]  DEFAULT ((0)) FOR [basico]
GO
ALTER TABLE [dbo].[CargoSet] ADD  CONSTRAINT [DF__CargoSet__sede__151B244E]  DEFAULT ('') FOR [sede]
GO

Anexo the project.



Please check carefully, it is important for the community.







Attachment: Prueba5_8afc37db.rar


LU luis December 10, 2019 08:42 AM UTC

I have solved the problem

 

Initial capital letter in field Name

 

<e-grid-column field="Id" isPrimaryKey="true" visible="false"></e-grid-column>

            <e-grid-column field="Codigo" headerText="Código" validationRules="@(new { required=true})" width="20"></e-grid-column>

            <e-grid-column field="Nombre" headerText="Nombre" validationRules="@(new { required=true})" width="80"></e-grid-column>

            <e-grid-column field="Basico" headerText="Básico" validationRules="@(new { required=true})" width="40" textAlign="Right" editType="numericedit" format="N2"></e-grid-column>

 

Change the model propery as Nullable

public partial class CargoSet

    {

        [Key]

        public Nullable<int> Id { get; set; }

        public string Codigo { get; set; }

        public string Nombre { get; set; }

 

In Startup file

 

services.AddControllersWithViews().AddNewtonsoftJson(options =>

            {

                options.SerializerSettings.ContractResolver = new DefaultContractResolver();

            });

 

Thank you


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team December 10, 2019 10:34 AM UTC

Hi Luis,

Thanks for the update.

We are happy to hear that you have you resolved the problem.  
  
Regards,  
Seeni Sakthi Kumar S 



AR Arian February 11, 2020 04:46 AM UTC

Hi, from your example 141281-dialog-template-urladaptor_Sample82178496.zip 

the CRUDModel value is null unless I enter a value for Order ID and Freight. Seems to be number related.  Any suggestions?

Thanks


LU luis February 11, 2020 05:21 AM UTC

I use a database with autoincremental id. I don't need to send that id value, I can leave it null or empty. That is why I have solved the problem for my case as explained.


DR Dhivya Rajendran Syncfusion Team February 11, 2020 06:48 AM UTC

Hi Arian, 

Greetings from Syncfusion support. 
 
Query : the CRUDModel value is null unless I enter a value for Order ID and Freight. Seems to be number related.  Any suggestions? 
 
From your shared sample we found that you were defined a number variables without a null coalescing operator so that we can’t able to  assign a null value to a number variable. Refer the below reference link for more information and you can resolve the reported problem by using null coalescing operator ( ? ) in that variable. 


Please change your controller side code as like given below. 


public class Orders 
        { 
            public Orders() 
            { 
 
            } 
            public Orders(long OrderId, string CustomerId, int EmployeeId, double Freight, DateTime OrderDate, string ShipCity) 
            { 
                ------ 
           } 
            public long? OrderID { get; set; } 
            public string CustomerID { get; set; } 
            public int EmployeeID { get; set; } 
            public double? Freight { get; set; } 
            public DateTime OrderDate { get; set; } 
            public string ShipCity { get; set; } 
        } 


Note : CRUD operations depends the primaryKey field and we did not specify the null value for primary key column so make sure to specify the unique value for that column. 

We also have client side validation support for Grid. Please refer the below documentation for more information. 



Please get back to us if you need further assistance. 

Regards, 
R.Dhivya 


Loader.
Live Chat Icon For mobile
Up arrow icon