Add and Edit not updating database

I am using Synfusion ASP.NET MVC with EF and SQL Server. I am new to this product and am battling a bit. I can populate the datagrid but when I try to Add or Edit records the changes are made in the grid but not in the database. I am attaching code below. I have tried googling but haven't found anything that worked. Can you help me?

[Index.cshtml]

@model AssetWaveWeb.ViewModels.FinancialPeriodViewModel

@{

    ViewData["Title"] = "Manage Financial Periods";

}


<!DOCTYPE html>

<html>

<head>

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

    <!-- Add the Syncfusion CSS and scripts -->

    <link rel="stylesheet" rel='nofollow' href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

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

</head>

<body>


    <!-- Add a container for the DataGrid -->

    <div id="FinancialPeriodGrid"></div>


    <script>

        // Load the Financial Periods data

        var financialPeriods = @Html.Raw(Json.Serialize(Model.FinancialPeriods));


        // Initialize the DataGrid

        var grid = new ej.grids.Grid({

            dataSource: financialPeriods,

            columns: [

                { field: 'FinancialPeriodId', headerText: 'Financial Period Id', isPrimaryKey: true, visible: false },

                { field: 'Code', headerText: 'Code', width: '120', validationRules: { required: true } },

                { field: 'StartMonth', headerText: 'Start Month', width: '150', textAlign: 'Center', validationRules: { required: true, number: true } },

                { field: 'ActiveFlag', headerText: 'Active Flag', width: '150', textAlign: 'Center', validationRules: { required: true } },

                { field: 'Description', headerText: 'Description', validationRules: { required: true } },

                { field: 'LastUpdated', headerText: 'Last Updated', width: '220', type: 'date', format: 'yyyy/MM/dd hh:mm', visible: true }

            ],

            height: 350,

            editSettings: {

                allowAdding: true,

                allowEditing: true,

                mode: 'Dialog'

            },

            toolbar: [

            'Add', 'Edit', 'Delete',

            {

                text: 'Exit',

                tooltipText: 'Exit to Menu',

                prefixIcon: 'e-cancel',

                click: function () {

                    window.location.rel='nofollow' href = '@Url.Action("Index", "Menu", new { menuId = 1100 })';

                }

            }, 'Search'

            ],


            allowPaging: true,

            pageSettings: {

                pageCount: 2,

                pageSizes: true

            },

        });


        // Render the DataGrid

        grid.appendTo('#FinancialPeriodGrid');

    </script>

</body>

</html>

[FinancialPeriodController.cs]

using AssetWaveWeb.Data;

using AssetWaveWeb.Models;

using AssetWaveWeb.ViewModels;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Linq;


namespace AssetWaveWeb.Controllers

{

    public class FinancialPeriodController : Controller

    {

        private readonly AppDbContext _context;


        public FinancialPeriodController(AppDbContext context)

        {

            _context = context;

        }


        // GET: FinancialPeriod

        public IActionResult Index()

        {

            var financialPeriods = _context.FinancialPeriods.ToList();

            var viewModel = new FinancialPeriodViewModel

            {

                FinancialPeriods = financialPeriods

            };

            return View(viewModel);

        }


        // POST: FinancialPeriod/Create

        [HttpPost]

        public IActionResult Create([FromBody] FinancialPeriod financialPeriod)

        {

            try

            {

                if (ModelState.IsValid)

                {

                    _context.FinancialPeriods.Add(financialPeriod);

                    _context.SaveChanges();

                    return Json(financialPeriod); // Return the created financial period with its updated data

                }

                return BadRequest(ModelState);

            }

            catch (Exception ex)

            {

                return BadRequest(ex.Message);

            }

        }


        // POST: FinancialPeriod/Update

        [HttpPost]

        public IActionResult Update([FromBody] FinancialPeriod financialPeriod)

        {

            try

            {

                if (ModelState.IsValid)

                {

                    _context.Update(financialPeriod);

                    _context.SaveChanges();

                    return Json(financialPeriod); // Return the updated financial period with its updated data

                }

                return BadRequest(ModelState);

            }

            catch (Exception ex)

            {

                return BadRequest(ex.Message);

            }

        }


        // POST: FinancialPeriod/Delete/5

        [HttpPost]

        public IActionResult Delete(int id)

        {

            try

            {

                var financialPeriod = _context.FinancialPeriods.Find(id);

                if (financialPeriod != null)

                {

                    _context.FinancialPeriods.Remove(financialPeriod);

                    _context.SaveChanges();

                    return Json(new { message = "Financial period deleted successfully" });

                }

                return NotFound();

            }

            catch (Exception ex)

            {

                return BadRequest(ex.Message);

            }

        }


        public IActionResult Edit(int id)

        {

            var financialPeriod = _context.FinancialPeriods.Find(id);

            if (financialPeriod == null)

            {

                return NotFound();

            }

            return View(financialPeriod);

        }


        [HttpPost]

        [ValidateAntiForgeryToken]

        public IActionResult Edit(int id, FinancialPeriod financialPeriod)

        {

            if (id != financialPeriod.FinancialPeriodId)

            {

                return NotFound();

            }


            if (ModelState.IsValid)

            {

                try

                {

                    _context.Update(financialPeriod);

                    _context.SaveChanges(); // Save changes to the database

                    return RedirectToAction(nameof(Index));

                }

                catch (Exception ex)

                {

                    TempData["ErrorMessage"] = "An error occurred while editing the financial period: " + ex.Message;

                }

            }

            return View(financialPeriod);

        }

    }

}

[FinancialPeriod.cs]

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;


namespace AssetWaveWeb.Models

{

    public class FinancialPeriod

    {

        [Key]

        public long FinancialPeriodId { get; set; }

        public string Code { get; set; }

        public int StartMonth { get; set; }

        public string ActiveFlag { get; set; }

        public string Description { get; set; }

        public DateTime? LastUpdated { get; set; }


        //public ICollection<RoleMenu> RoleMenus { get; set; }

    }

}



[FinancialPeriodViewModel]

using AssetWaveWeb.Models;

using System.Collections.Generic;


namespace AssetWaveWeb.ViewModels

{

    public class FinancialPeriodViewModel

    {

        public List<FinancialPeriod> FinancialPeriods { get; set; }

    }

}



.



19 Replies 1 reply marked as answer

HS Hemanthkumar S Syncfusion Team August 25, 2023 09:11 AM UTC

Hi Brian Collings,


Greetings from Syncfusion support.


Query: Add and Edit not updating database


Based on the information you've provided, it's clear that you're currently rendering the Grid using local data. However, it's important to note that any modifications made to the grid's dataSource won't automatically synchronize with the database when using local data. Based on the code example you shared, it seems that you intend to transmit newly added or edited data to the server for storage in the database.


To address this requirement, we highly recommend adopting the UrlAdaptor remote data service. By leveraging the UrlAdaptor, you'll have the capability to perform a variety of server-side actions, including adding, editing, deleting, filtering, sorting, paging, and more. This approach empowers you to interact with the server to manage data changes effectively, ensuring that the changes you make to the grid's data are synchronized with the database accurately.


For more information, please refer to the below code example, screenshot, documentation, and attached sample.


[Views\Home\Index.cshtml]

 

<div id="Grid"></div>

<script>

    var data = new ej.data.DataManager({

        url: '/Home/UrlDatasource',

        insertUrl: '/Home/Insert',

        updateUrl: '/Home/Update',

        removeUrl: '/Home/Remove',

        adaptor: new ej.data.UrlAdaptor()

    });

    var grid = new ej.grids.Grid({

        dataSource: data,

        allowSorting: true,

        columns: [

            { field: 'OrderID', headerText: 'Order ID', isPrimaryKey: true },

            { field: 'CustomerID', headerText: 'Customer ID', validationRules: { required: true } },

            { field: 'Freight', headerText: 'Freight', width: '150', textAlign: 'Center', validationRules: { required: true, number: true } },

            { field: 'OrderDate', headerText: 'Order Date', width: '220', type: 'datetime', format: 'yyyy/MM/dd hh:mm', editType: 'datetimepickeredit', visible: true }

        ],

        height: 350,

        editSettings: {

            allowAdding: true,

            allowEditing: true,

            allowDeleting: true,

            mode: 'Dialog'

        },

        toolbar: [

            'Add', 'Edit', 'Delete', 'Search'

        ],

        allowPaging: true,

        pageSettings: {

            pageCount: 2,

            pageSizes: true

        },

    });

    grid.appendTo('#Grid');

</script>

 

[Controllers\HomeController.cs]

 

        public ActionResult UrlDatasource(TestDm dm)

        {

            IEnumerable DataSource = orddata.ToList();

            DataOperations operation = new DataOperations();

 

            if (dm.Search != null && dm.Search.Count > 0)

            {

                DataSource = operation.PerformSearching(DataSource, dm.Search);  //Search

           }

            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting

            {

                DataSource = operation.PerformSorting(DataSource, dm.Sorted);

            }

            if (dm.Where != null && dm.Where.Count > 0) //Filtering

           {

                DataSource = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);

            }

            int count = DataSource.Cast<OrdersDetails>().Count();

            if (dm.Skip != 0)

            {

                DataSource = operation.PerformSkip(DataSource, dm.Skip);   //Paging

            }

            if (dm.Take != 0)

            {

                DataSource = operation.PerformTake(DataSource, dm.Take);

            }

            return dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource);

        }

        public ActionResult Update(CRUDModel<OrdersDetails> myObject)

        {

            // Update the data

            var ord = myObject;

            OrdersDetails val = orddata.Where(or => or.OrderID == ord.Value.OrderID).FirstOrDefault();

            if (val != null)

            {

                val.OrderID = ord.Value.OrderID;

                val.EmployeeID = ord.Value.EmployeeID;

                val.CustomerID = ord.Value.CustomerID;

                val.Freight = ord.Value.Freight;

                val.OrderDate = ord.Value.OrderDate;

                val.ShipCity = ord.Value.ShipCity;

                val.ShipAddress = ord.Value.ShipAddress;

                val.ShippedDate = ord.Value.ShippedDate;

            }

 

            return Json(ord.Value);

 

        }

        public ActionResult Insert(OrdersDetails value)

        {

            // Insert the data

            var ord = value;

            orddata.Insert(0, ord);

            return Json(value);

        }

        public void Remove(int key)

        {

            // Remove the data

            orddata.Remove(orddata.Where(or => or.OrderID == key).FirstOrDefault());

        }


A screenshot of a computer

Description automatically generated


A computer screen shot of a computer

Description automatically generated


Url adaptor: https://ej2.syncfusion.com/javascript/documentation/data/adaptors#url-adaptor


Please feel free to contact us if you require any further assistance. We are always available and eager to help you in any way we can.


Regards,

Hemanth Kumar S


Attachment: 3320111498785947_e523b66e.zip


BC Brian Collings August 26, 2023 08:13 AM UTC

Hi  Hemanth

Thank you for your reply.

Give me some time to understand it and apply it to my application and I willgive you feedback.

Regards

Brian Collings




HS Hemanthkumar S Syncfusion Team August 28, 2023 04:02 AM UTC

Hi Brian Collings,


Sure, we will wait to hear from you.


Regards,

Hemanth Kumar S



BC Brian Collings August 31, 2023 06:41 AM UTC

Hi  Hemanth Kumar S

I am having prpblems applying your solution to my application. I think the issue is because it is a Framework 4.6 solution and I'm working with .NET 6. 

Can you send me an example using .NET 6 please.

Regards

Brian Collings




HS Hemanthkumar S Syncfusion Team September 4, 2023 03:10 PM UTC

Hi Brian Collings,


Before we proceed with providing a solution, we need some information to better understand the issue you are facing. Please provide us with the following details:


  1. Provide a detailed description of the issue you are currently facing while implementing the given solution in .NET 6.
  2. Are you encountering any script error or package error while implementing the given solution in .NET 6? If so, provide an image or description of that error, as it will assist us in identifying the cause of the issue.
  3. Share the complete code for rendering the Grid. Having the full code will allow us to review the implementation and potentially identify any issues or suggest improvements.
  4. Sharing a video demonstration would greatly assist us in better understanding your issue.
  5. Share the reproducible sample that showcases the issue. Having a sample will enable us to directly analyze and validate the problem, which can lead to a faster resolution.


We appreciate your cooperation in providing us with the requested information, as it will help us provide a more effective solution to your query.


Regards,

Hemanth Kumar S



BC Brian Collings September 12, 2023 11:37 AM UTC

Hi Herman

I'm attaching copies of Model, View and Controller for this problem.

My problem is nothing happens. When the view is displayed there is no table containing records and there is no toolbar.

I don't know if the problem is in the controller or the view or maybe somewhere else.

I don't have much experience with ASP.NET MVC .NET 6 so I'm still learning. 

Everything was working fine until I added Url Adaptor. Since then nothing has worked no matter how much I tried to fix it.

Let me know if you need anything else.

Regards

Brian Collings



Attachment: Code_Samples_2a67ad2f.7z


HS Hemanthkumar S Syncfusion Team September 15, 2023 03:28 PM UTC

Hi Brian Collings,


Based on the information you've provided, it appears that you're encountering an issue where there are no records in the table, and the Grid's toolbar isn't rendering correctly. After reviewing your code, we've noticed that you're rendering the Grid using the ASP.NET Core approach rather than the ASP.NET MVC approach. Given that you're working on an MVC project, we recommend rendering the Grid using the ASP.NET MVC approach, as outlined in the documentation provided below.


Getting Started with ASP.NET MVC Grid Control: https://ej2.syncfusion.com/aspnetmvc/documentation/grid/getting-started-mvc


If the above information is not helpful, then we need some information to better validate the reported issue.


  1. Have you encountered any script errors in the browser console when experiencing the issue of no records in the table and the toolbar not rendering correctly in the Grid? If script errors are present, please provide either a screenshot or a description of the error message. This information will help us pinpoint the root cause of the problem.
  2. Furthermore, we suggest verifying whether the actionFailure event of the Grid is triggered when encountering the no records in the table and the toolbar not rendering correctly in the Grid. This event is triggered whenever a Grid action fails to accomplish the intended outcome.

actionFailure: https://ej2.syncfusion.com/documentation/api/grid/#actionfailure

  1. Share the reproducible sample that showcases the issue. Having a sample will enable us to directly analyze and validate the problem, which can lead to a faster resolution.


Regards,

Hemanth Kumar S



BC Brian Collings September 15, 2023 03:45 PM UTC

Hi Hemanth

Thanks for your reply.

I will use your suggestions and let you know what happens.

By the way, there is data in the database table.

Regards

Brian Collings




HS Hemanthkumar S Syncfusion Team September 19, 2023 03:17 AM UTC

Hi Brian Collings,


Sure, we will wait to hear from you.


Regards,

Hemanth Kumar S



BC Brian Collings September 28, 2023 01:10 PM UTC

Hi  Hemanth Kumar S

I took a working AP.NET Core 6 application without Syncfusion controls and tried to ad a Suncfusion datagrid, but it's not working.

I'm attaching a copy of the application. The datagrid is in Pages/Movies/Index.cshtml.

Can you tell me what I'm doing wrong?

After I get this working I can look at Adding, Editing and Deleting data.

Regards

Brian Collings


Attachment: RazorPagesMovie_752d4517.7z


HS Hemanthkumar S Syncfusion Team September 29, 2023 10:27 AM UTC

Hi Brian Collings,

Currently, we are validating your query with the shared information. We will update further details on or before October 4, 2023. We appreciate your patience until then.



BC Brian Collings September 29, 2023 11:21 AM UTC

Hi Hemanth

Thank you. I'll wait until you are ready.

Regards

Brian Collings



HS Hemanthkumar S Syncfusion Team October 4, 2023 10:09 AM UTC

Hi Brian Collings,


Query: I took a working AP.NET Core 6 application without Syncfusion controls and tried to ad a Suncfusion datagrid, but it's not working.


Based on the provided information, it appears you are facing an issue in rendering the Syncfusion EJ2 Grid on your Razor Page. Upon reviewing your shared sample, we have identified that you haven't yet installed the Syncfusion NuGet package, added the Syncfusion ASP.NET Core Tag Helper, included the required style sheets and script references, and registered the Syncfusion Script Manager.


To assist you in resolving this matter, we kindly recommend referring to the documentation provided below, which outlines the necessary steps for adding these mentioned requirements:


https://ej2.syncfusion.com/aspnetcore/documentation/grid/getting-started-core


Also from your shared sample, we identified that you want to use UrlAdaptor for the data processing in the Grid. Since the POST request is used for calling the URL method in the Movies Index page, we need to configure ‘XSRF-TOKEN’ in the Program.cs page like given below


[Program.cs]

 

builder.Services.AddMvc().AddJsonOptions(o =>

{

    o.JsonSerializerOptions.PropertyNamingPolicy = null;

    o.JsonSerializerOptions.DictionaryKeyPolicy = null;

});

builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");


Then, add the verification token to the Grid data source’s header property in its load event and include the AntiForgeryToken as explained in the following code snippet,


[Movies\Index.cshtml]

 

@Html.AntiForgeryToken()

<ejs-grid id="Grid" load="onLoad" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })">

.

.

 

<script>

    // Grid’s load event handler

    function onLoad() {

        this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': $("input:hidden[name='__RequestVerificationToken']").val() }];

    }

</script>


For more information, please refer to the below documentation, the attached sample, and the video.


How to Render Grid in ASP.NET Core Razor Page: https://support.syncfusion.com/kb/article/10443/how-to-render-grid-in-asp-net-core-razor-page


How to use UrlAdaptor in Asp.Net Core Razor Page: https://support.syncfusion.com/kb/article/8165/how-to-use-urladaptor-in-asp-net-core-razor-page


Please feel free to contact us if you require any further assistance. We are always available and eager to help you in any way we can.


Regards,

Hemanth Kumar S


Attachment: sample_and_video_2a0c451c.zip

Marked as answer

BC Brian Collings October 4, 2023 11:54 AM UTC

Thanks Hemanth Kumar S

I appreciate you help and your patience with a beginner.

I've started applying your suggestions and will come back you you if I have problems or hopefully, if everything works.

Regards

Brian Collings




HS Hemanthkumar S Syncfusion Team October 5, 2023 03:20 AM UTC

Hi Brian Collings,


Sure, we will wait to hear from you.


Regards,

Hemanth Kumar S



BC Brian Collings October 15, 2023 11:56 AM UTC

Hi Hemanth Kumar S

I think I've got it. The insert, update and delete are all working and updating the database on the server.

I've attached my code.

Thank you for your help.

Regards

Brian Collings



Attachment: Attachments_fc94ffcd.7z


HS Hemanthkumar S Syncfusion Team October 17, 2023 03:34 AM UTC

Hi Brian Collings,


Thank you for your message. We are pleased to hear that you found our suggested approach helpful. If you feel that it adequately addresses your concern, please consider accepting it as the solution. Doing so will make it easier for other members to find the solution quickly.


Regards,

Hemanth Kumar S



BC Brian Collings October 17, 2023 04:50 AM UTC

I'm happy to accept it as the solution. How do I do that?




AS Aruna Shree Natarajan Syncfusion Team November 1, 2023 04:04 AM UTC

Hi Brian,

You have Mark as answer option below each reply.


Which reply you want to mark answer, click the “Mark as answer“ link.

Once you Marked Answered. It’s will show like below.
 

Please let us know if you need any further assistance.


Loader.
Up arrow icon