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

"An item with the same key has already been added" error while creating item in kendo grid

2 Answers 969 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Vishal
Top achievements
Rank 1
Vishal asked on 28 Jan 2021, 06:16 AM

When I call the Create method of kendo grid its giving an exception - ''"An item with the same key has already been added". I checked that their is no any duplicate property name in the model, Only one grid on the page. Not sure what causing this error. Appreciate your help in advance.

Inner Exception : 

at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)<br>   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)<br>   at System.Collections.Generic.CollectionExtensions.ToDictionaryFast[TKey,TValue](TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer)<br>   at System.Web.Mvc.ModelBindingContext.get_PropertyMetadata()<br>   at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)<br>   at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)<br>   at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)<br>   at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)<br>   at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)<br>   at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)<br>   at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)<br>   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState)

 

 

Grid : 

@(Html.Kendo().Grid<PersonViewModel>(false)

                            .HtmlAttributes(new { @style = "height: 100%;" })
                            .Name("ContactGrid")
                            .ToolBar(toolbar => toolbar.Create())
                            .toolbar(tools =>
                            {
                                tools.custom().name("addnewcontact").text("add new contact".translate()).htmlattributes(new
                                {
                                    id = "addnewcontact"
                                });
                            })
                            .Excel(e => { e.Filterable(true); e.AllPages(true); e.ForceProxy(true); e.ProxyURL("/Localized/" + nameof(LocalizedController.ExportToExcel)); })
                            .Editable(e =>
                            {
                                e.Enabled(true)
                                .DisplayDeleteConfirmation(true)
                               .Mode(GridEditMode.PopUp).TemplateName("PersonEditor")
                                .Window(w =>
                                {
                                    w.Scrollable(true)
                                    .Resizable()
                                    .Height(245).Width(400);
                                });
                            })

                    .DataSource(datasource => datasource
                    .Custom()
                    .Type("aspnetmvc-ajax")
                    .Transport(t =>
                    {
                        t.Read(r => r.Action("Contacts_Read", "DynamicDiscountingOffer").Data("getAdditionalData").Type(HttpVerbs.Get));
                        t.Create(c => c.Action("Contacts_Create", "DynamicDiscountingOffer").Data("getAdditionalDataToCreateContact"));
                        t.Create(c => c.Action("Contacts_Create", "DynamicDiscountingOffer"));
                    })

                    .Schema(s => s
                    .Model(model =>
                    {
                        model.Id(p => p.VR_PersonId);
                        model.Field(nameof(PersonViewModel.VR_Id), typeof(int?)).DefaultValue(VrId);
                        model.Field(nameof(PersonViewModel.FirstName), typeof(string));
                        model.Field(nameof(PersonViewModel.LastName), typeof(string));
                        model.Field(nameof(PersonViewModel.Email), typeof(string));
                    })
                    .Errors("Errors")
                    .Data("Data")
                    .Total("Total")
                    )
                    .PageSize(10)
                    .ServerSorting(true)
                    .ServerPaging(true)
                    .ServerFiltering(true)
                    .ServerGrouping(false)
                    .ServerAggregates(false)
                    .Events(events => events.Error("error_handler"))
                   )
                   .Pageable(p => { p.Refresh(true); p.PageSizes(new int[] { 10, 20, 50, 100, 200, 2000, 5000 }); })
                    .Columns(columns =>
                    {
                        columns.Bound(c => c.FirstName).Width(140);
                        columns.Bound(c => c.LastName).Width(190);
                        columns.Bound(c => c.Email).Width(250);
                        columns.Command(command =>
                        {
                            ///command.Edit().UpdateText("Submit".Translate()).Visible("editVisible").Text("Edit".Translate());
                            command.Custom("View").Visible("viewVisible").Text("View".Translate()).Click("showDetails");
                            command.Custom("Delete").Visible("deleteVisible").Text("Delete".Translate()).Click("DeleteRow");
                        }).Width(85).MinResizableWidth(85);

                    }
    )
    )

 
[DataContract]
    [Serializable]
    public class PersonViewModel : IValidatableObject
    {
        public int VR_PersonId { get; set; }
 
        [DataMember]
        public int VR_Id { get; set; }
 
        [DataMember]
        public string VendorId { get; set; }
 
        [DataMember]
        public Nullable<Guid> UserId { get; set; }
         
        [DataMember]
        public Nullable<System.DateTime> StartDate { get; set; }

}

 

2 Answers, 1 is accepted

Sort by
0
Vishal
Top achievements
Rank 1
answered on 28 Jan 2021, 06:20 AM
Sorry,Below is the correct model => 
 [DataContract]
    [Serializable]
    public class PersonViewModel : IValidatableObject
    {
        public int VR_PersonId { get; set; }
 
        [DataMember]
        public int VR_Id { get; set; }
 
        [DataMember]
        public string VendorId { get; set; }
 
        [DataMember]
        public Nullable<Guid> UserId { get; set; }
         
        [DataMember]
        public Nullable<System.DateTime> StartDate { get; set; }
 
        [DataMember]
        public Nullable<System.DateTime> EndDate { get; set; }
       
 
        [DataMember]
        public string FirstName { get; set; }
 
        [DataMember]
        public string LastName { get; set; }
 
        [DataMember]
        public string Email { get; set; }       
 
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (string.IsNullOrWhiteSpace(Email) || string.IsNullOrWhiteSpace(HttpUtility.HtmlDecode(Email)))
            {
                yield return new ValidationResult("Email is Required".Translate(), new[] { nameof(Email) });
            }
        }
    }
}
0
Anton Mironov
Telerik team
answered on 29 Jan 2021, 02:53 PM

Hi Vishal,

Thank you for the provided details.

As this one is a copy of your other ticket in the private system(#1504304), I will paste my response here. I recommend moving the discussion here, so the resolving of the issue will be available for the whole community. The other thread will be closed now.

In order to continue the investigation:

The fastest route to getting you up and running is if you could provide a runnable, isolated, sample project. Examining this project will let us replicate the issue locally and further troubleshoot it.

In order to help you create the reproducible, I have gone ahead and created a starter project for you. It already has all the dependencies and a view/controller with a Grid.

Please take the following steps:

1. Download, unblock and extract the attached solution
2. Open it in  VS2019 and update the following files with your problematic code
2.1 Controllers/GridController.cs
2.2 Views/Home/Index.cshtml
3. Run the project and confirm that it reproduces the problem at runtime
4. Close VS2019, then open the project in File Explorer and delete the bin and obj folders
5. Zip up the solution and attach it to your next reply.

Send me a runnable sample of your project or use the attached sample.

Looking forward to hearing back from you.

 

Kind Regards,
Anton Mironov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Grid
Asked by
Vishal
Top achievements
Rank 1
Answers by
Vishal
Top achievements
Rank 1
Anton Mironov
Telerik team
Share this question
or