This is a migrated thread and some comments may be shown as answers.

Adding a new item does not save to the database

5 Answers 361 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
Lawrence
Top achievements
Rank 1
Lawrence asked on 08 May 2018, 12:38 PM

Hello

 

I am currently trying out Kendo UI for jQuery. I have an issue with the combobox where it does not save a new item to my database once I added the item. It seems to save it in localstorage for the duration of the session. I am new to this, so I am probably doing something wrong here. I have followed the example from the demo and the backend service. Can someone please tell me what I am doing wrong here.

 

Here is the code for my view page which sits in my app:

<div id="countries">
                            <div class="demo-section k-content">
                                <h4>Enter a Country name</h4>
                                <input id="countries" style="width: 100%;" />
                                <div class="demo-hint">e.g. 'South Africa'</div>
                            </div>
 
                            <script id="noDataTemplate" type="text/x-kendo-tmpl">
                                <div>
                                    No data found. Do you want to add new item - '#: instance.text() #' ?
                                </div>
                                <br />
                                <button class="k-button" onclick="addNew('#: instance.element[0].id #', '#: instance.text() #')">Add new item</button>
                            </script>
 
                            <script>
                                function addNew(widgetId, value) {
                                    var widget = $("#" + widgetId).getKendoComboBox();
                                    var dataSource = widget.dataSource;
 
                                    if (confirm("Are you sure you want to add this Country?")) {
                                        dataSource.add({
                                            CountryIdentifier: 0,
                                            CountryName: value
                                        });
 
                                        dataSource.one("sync", function () {
                                            widget.select(dataSource.view().length - 1);
                                        });
 
                                        dataSource.sync();
                                    }
                                };
                            </script>
 
                            <script>
                                $(document).ready(function () {
                                    var crudServiceBaseUrl = "http://localhost:49517";
                                    var dataSource = new kendo.data.DataSource({
                                        batch: true,
                                        transport: {
                                            read: {
                                                url: crudServiceBaseUrl + "/Countries",
                                                dataType: "jsonp"
                                            },
                                            create: {
                                                url: crudServiceBaseUrl + "/Countries/Create",
                                                dataType: "jsonp"
                                            },
                                            parameterMap: function (options, operation) {
                                                if (operation !== "read" && options.models) {
                                                    return { models: kendo.stringify(options.models) };
                                                }
                                            }
                                        },
                                        schema: {
                                            model: {
                                                id: "CountryIdentifier",
                                                fields: {
                                                    CountryIdentifier: { type: "number" },
                                                    CountryName: { type: "string" }
                                                }
                                            }
                                        }
                                    });
 
                                    $("#countries").kendoComboBox({
                                        filter: "startswith",
                                        dataTextField: "CountryName",
                                        dataValueField: "CountryIdentifier",
                                        dataSource: dataSource,
                                        noDataTemplate: $("#noDataTemplate").html()
                                    });
                                });
                            </script>
                        </div>

 

Here is the code for my controller which sits in my API:

public class CountriesController : Controller
    {
        public ActionResult Index()
        {
            return this.Jsonp(CountryRepository.All());
        }
 
        public JsonResult Update()
        {
            var models = this.DeserializeObject<IEnumerable<CountryViewModel>>("models");
            if (models != null)
            {
                CountryRepository.Update(models);
            }
            return this.Jsonp(models);
        }
 
        public ActionResult Destroy()
        {
            var countries = this.DeserializeObject<IEnumerable<CountryViewModel>>("models");
 
            if (countries != null)
            {
                CountryRepository.Delete(countries);
            }
            return this.Jsonp(countries);
        }
 
        public ActionResult Create()
        {
            var countries = this.DeserializeObject<IEnumerable<CountryViewModel>>("models");
            if (countries != null)
            {
                CountryRepository.Insert(countries);
            }
            return this.Jsonp(countries);
        }
 
        public JsonResult Read(int skip, int take)
        {
            IEnumerable<CountryViewModel> result = CountryRepository.All().OrderByDescending(p => p.CountryIdentifier);
 
            result = result.Skip(skip).Take(take);
 
            return this.Jsonp(result);
        }
    }

 

Here is the code for my ViewModel which sits in my API:

public class CountryViewModel
    {
        public int? CountryIdentifier { get; set; }
        public string CountryName { get; set; }
        public string CreatedBy { get; set; }
        public string FK_CreatedByID { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> DateCreated { get; set; }
        public string LastEditedBy { get; set; }
        public string FK_LastEditedByID { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> DateLastEdited { get; set; }
    }

 

And here is the code for my CountryRepository which sits in my API:

public static class CountryRepository
    {
        public static IList<CountryViewModel> All()
        {
            var result = HttpContext.Current.Session["Countries"] as IList<CountryViewModel>;
 
            if (result == null)
            {
                HttpContext.Current.Session["Countries"] = result =
                    new OldMutualDataContext().Countries.Select(c => new CountryViewModel
                    {
                        CountryIdentifier = c.CountryIdentifier,
                        CountryName = c.CountryName,
                        CreatedBy = c.CreatedBy,
                        FK_CreatedByID = c.FK_CreatedByID,
                        DateCreated = c.DateCreated,
                        LastEditedBy = c.LastEditedBy,
                        FK_LastEditedByID = c.FK_LastEditedByID,
                        DateLastEdited = c.DateLastEdited
                    }).ToList();
            }
 
            return result;
        }
 
        public static CountryViewModel One(Func<CountryViewModel, bool> predicate)
        {
            return All().FirstOrDefault(predicate);
        }
 
        public static void Insert(CountryViewModel country)
        {
            var first = All().OrderByDescending(c => c.CountryIdentifier).FirstOrDefault();
            if (first != null)
            {
                country.CountryIdentifier = first.CountryIdentifier + 1;
            }
            else
            {
                country.CountryIdentifier = 0;
            }
 
            All().Insert(0, country);
        }
 
        public static void Insert(IEnumerable<CountryViewModel> countries)
        {
            foreach (var country in countries)
            {
                Insert(country);
            }
        }
 
        public static void Update(CountryViewModel country)
        {
            var target = One(c => c.CountryIdentifier == country.CountryIdentifier);
            if (target != null)
            {
                target.CountryName = country.CountryName;
                target.LastEditedBy = country.LastEditedBy;
                target.FK_LastEditedByID = country.FK_LastEditedByID;
                target.DateLastEdited = country.DateLastEdited;
            }
        }
 
        public static void Update(IEnumerable<CountryViewModel> countries)
        {
            foreach (var country in countries)
            {
                Update(country);
            }
        }
 
        public static void Delete(CountryViewModel country)
        {
            var target = One(c => c.CountryIdentifier == country.CountryIdentifier);
            if (target != null)
            {
                All().Remove(target);
            }
        }
 
        public static void Delete(IEnumerable<CountryViewModel> countries)
        {
            foreach (var country in countries)
            {
                Delete(country);
            }
        }
    }

 

Help would be appreciated.

 

Thank You

5 Answers, 1 is accepted

Sort by
0
Joana
Telerik team
answered on 10 May 2018, 07:20 AM
Hello Lawrence,

I assume that the issue stems from the insertion of dataItem with CountryIdentifier: 0. If there is already an item that has 0 for CountryIdentifier the dataSource is trying to update the existing one and as there is no Update operation setup the item will not be modified. I suggest that you insert the dataItem without explicitly setting its identifier:

dataSource.add({
    CountryName: value
});

Have a look at the following example which I prepared for you based on your code:

https://dojo.telerik.com/eWoREyak


Let me know if you have further questions.

Regards,
Joana
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Lawrence
Top achievements
Rank 1
answered on 10 May 2018, 07:51 AM

Hello Joana

 

Thank you for the response. How can I adjust the code in the controller to insert a generated GUID instead of an integer? I think that would work much better and would resolve my issue as well, I'm just not sure how to change it from integer to generate a GUID.

0
Joana
Telerik team
answered on 11 May 2018, 11:25 AM
Hi Lawrence,

The below code automatically inserts the Country with CountryID with value equal to the last id incremented by 1. I believe this is similar to the approach of using Guid and then generating new Guid prior to adding an item in the dataSource.

dataSource.add({
    CountryName: value
});

However, if you really want to use Guid you should just update the Model CountryIdentifier and apply the changes to the datasource. It's analogical to the usage of integers.

Regards,
Joana
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Lawrence
Top achievements
Rank 1
answered on 12 May 2018, 02:44 PM

Hi Joana

I have tried with the code you have given me but it is still not saving to the database. It only saves in my browser session

0
Joana
Telerik team
answered on 16 May 2018, 05:54 AM
Hello Lawrence,

On first sight I am not able to diagnose what's causing the issue on your side. Could you please send us your sample testing project so that I could examine it further and apply changes if necessary?

Could you please test the behavior with autoSync configuration setting of the dataSource set to true and verify that the Insert method is called?

https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/autosync

You might find useful the following resources:

https://docs.telerik.com/kendo-ui/framework/datasource/crud#remote-transport-crud-operations

https://github.com/telerik/kendo-ui-demos-service/blob/master/demos-and-odata-v3/KendoCRUDService/Controllers/ProductsController.cs 

I am looking forward to your reply.

Regards,
Joana
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
ComboBox
Asked by
Lawrence
Top achievements
Rank 1
Answers by
Joana
Telerik team
Lawrence
Top achievements
Rank 1
Share this question
or