[asp.net-mvc] An item with the same key has already been added

I get this error whenever I submit the form also the action method is not being called because of this:

An item with the same key has already been added.

And the exception details:

[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +9382923 System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) +252
System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer) +91
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +228 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +392
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +473
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.b__4() +65 System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +44 System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

ViewPage

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/XYZ.Master"
    Inherits="System.Web.Mvc.ViewPage<XYZ.Models.Admin.AdminSegmentCommissionsModel>" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        Create
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <% using (Html.BeginForm()) {%>    
            <div class="box3">
                <div class="userinfo">
                    <h3>Admin Segment Commissions</h3>
                </div>
                <div class="buttons-panel">
                    <ul>
                       <li>
                           <input type="submit" value="Save" class="save" />
                       </li>
                       <li>
                           <%:Html.ActionLink("Cancel", "Index", new { controller = "AdminSegmentCommissions" }, new { @class = "cancel" })%>
                           <%--<input type="button" value="Cancel" class="cancel" onclick="document.location.href='/AirlineLedgerTransactionReceiver/Index'" />--%>
                       </li>
                   </ul>
               </div>
           </div>
           <div class="row-1">
               <div class="form-box1 round-corner">
                   <div class="form-box1-row">
                       <div class="form-box1-row-content float-left">
                           <div>
                               <label>
                                   <%: Html.LabelFor(model => model.FromSegmentNumber) %></label>
                                   <%: Html.TextBoxFor(model => model.FromSegmentNumber) %>
                                   <%: Html.ValidationMessageFor(model => model.FromSegmentNumber) %>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      <%} %>

This question is related to asp.net-mvc

The answer is


In MVC 5 I found that temporarily commenting out references to an Entity Framework model, and recompiling the project side stepped this error when scaffolding. Once I finish scaffolding I uncomment the code.

public Guid CreatedById { get; private set; }
// Commented out so I can scaffold: 
// public virtual UserBase CreatedBy { get; private set; }

I had this issue on the DBContext. Got the error when I tried run an update-database in Package Manager console to add a migration:

public virtual IDbSet Status { get; set; }

The problem was that the type and the name were the same. I changed it to:

public virtual IDbSet Statuses { get; set; }


I have had the same error. When i check the code then i found that declare "GET" request in my angular (font-end) side and declare "POST" request in the ASP.net (back-end) side. Set POST/GET any one in both side. Then solved the error.


I have had the same error. And after I have already thought my mind is broken, because I had rename almost all my models properties the solution was delete one reference on All Syncfusion Controls and add references to the individual controls of this controls. (From Nuget)


In my case the root of the problem was duplicate property name in the client json which only differed by case sensitivity.


I had the same issue , i was foreach looping over my object and adding the result into a Dictionary<string, string> and i had a `Duplicate in the key from the database

 foreach (var item in myObject)
        {
            myDictionary.Add(Convert.ToString(item.x), 
                                   item.y);

        }

item.x had a duplicate value


I had the same problem and this is how I solved it. I had a duplicate property with the same name in my ViewModel. One Property was in BaseViewModel and another is in derived Model.

public class BaseviewModel{
  public int UserId { get; set; }
}


 public class Model : BaseViewModel
 {
     public int UserId { get; set; }
 }

I changed that to

public class BaseviewModel{
   public int UserId { get; set; }
}


public class Model : BaseViewModel
{
    public int User_Id { get; set; }
}

Now it is working fine.


I have had the same error but b/c of diff reason. Using Entity framework. One more thing I need to add here before I share my code and solution, I had a break point on controller method but it was not breaking there, just throwing exception 500 internal server error.

I was posting data from view to controller through ajax (http post). The model I was expecting as a parameter was a class. It was inherited with some other class.

public class PurchaseOrder : CreateUpdateUserInfo
    {
        public PurchaseOrder()
        {
            this.Purchase_Order_Items = new List<clsItem>();
        }

        public int purchase_order_id { get; set; }
        public Nullable<int> purchase_quotation_id { get; set; }
        public int supplier_id { get; set; }
        public decimal flat_discount { get; set; }
        public decimal total { get; set; }
        public decimal net_payable { get; set; }
        public bool is_payment_complete { get; set; }
        public decimal sales_tax { get; set; }
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public bool IsDeleted { get; set; }
        public List<clsItem> Purchase_Order_Items { get; set; }
    }

 public class CreateUpdateUserInfo
    {
        public DateTime CreatedOn { get; set; }
        public int CreatorUserID { get; set; }
        public string CreatorUserName { get; set; }
        public DateTime UpdatedOn { get; set; }
        public int UpdatorUserID { get; set; }
        public string UpdatorUserName { get; set; }
        public bool IsDeleted { get; set; }
    }

and in view

                var model = {
                supplier_id : isNaN($scope.supplierID) || 0 ? null : $scope.supplierID,
                flat_discount : 0,
                total : $scope.total,
                net_payable :  $scope.total,
                is_payment_complete :  true,
                sales_tax:0,
                Purchase_Order_Item: $scope.items
            };
            var obj = {
                method: 'POST',
                url: 'Purchase/SaveOrder',
                dataType: 'json',
                data: JSON.stringify(model),
                headers: { "Content-Type": "application/json" }
            };

            var request = $rootScope.AjaxRequest(obj);
            request.then(function (response) {
                var isError = response.data.MessageType === 1;
                $rootScope.bindToaster(response.data.MessageType,response.data.Message);
                //$('html, body').animate({ scrollTop: 0 }, 'slow');
                if(!isError){
                    //$scope.supplierID =undefined;
                }
            }, function (response) {
                $rootScope.bindToaster(2,response.data);
                console.log(response);
            });

Simply removed duplicated fields from PurchaseOrder class and it worked like a charm.


Here is what I did to find out the key that was being added twice. I downloaded the source code from http://referencesource.microsoft.com/DotNetReferenceSource.zip and setup VS to debug framework source. Opened up Dictionary.cs in VS ran the project, once page loads, added a debug at the line ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); and was able to see the 'key' value. I realized that in the JSON one letter of a variable was in upper case but in my model it was lowercase. I fixed the model and now the same code works.


I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an IndexAttribute like below. Commenting out one of them and recompiling resulted in scaffolding the MVC 5 controller with views, using Entity Framework succeeding. Mysteriously, when I uncommented the attribute, recompiled, and tried again, the scaffolder ran just fine.

Perhaps the underlying entity data model or "something" was cached/corrupted, and removing and re-adding the IndexAttribute simply triggered a rebuild of that "something".

[Index(IsUnique = true)]
public string Thing1 { get; set; }

[Index(IsUnique = true)]
public string Thing2 { get; set; }

I found the answer.It was because of the variables. Like int a and string a. there were two variables with the same name.


I had same issue. It appeard to me after migrating to MVC 5 from MVC 3.

I had custom editor template and had to use it like this before:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField", this.ViewData)

To resolve issue I had to remove passing ViewData object. So at the end I had:

@Html.EditorFor(model => model.MyProperty, "MyCustomTemplateName", "MyPropertyField")

Hope it helps.


Another way to encounter this error is from a dataset with unnamed columns. The error is thrown when the dataset is serialized into JSON.

This statement will result in error:

select @column1, @column2

Adding column names will prevent the error:

select @column1 as col1, @column2 as col2

I had 2 model properties like this

public int LinkId {get;set;}
public int LinkID {get;set;}

it is strange that it threw this error for these 2 haha..


I had a similar problem and found that it was because I had a similarly named public property (that should have been private) that only differed in case.

public string PropertyName {get;set;} // actually set propertyName, get propertyName
public string propertyName {get;set;}

should have been

public string PropertyName {get;set;} 
private string propertyName {get;set;}

I had the problem not in my C# model, but in the javascript object I was posting using AJAX. I'm using Angular for binding and had a capitalized Notes field on the page while my C# object was expecting lower-case notes. A more descriptive error would sure be nice.

C#:

class Post {
    public string notes { get; set; }
}

Angular/Javascript:

<input ng-model="post.Notes" type="text">

I would like to add an answer that I do not see here. It is very related to the accepted answer, however, I did not have duplicated properties on my model, it was an issue with my Javascript.

I was doing some Ajax save where I was rebuilding the model to send back to the server. When I had first initialized the page I set my original model to a variable:

var currentModel = result.Data;

My result.Data has a property: result.Data.Items

So, some time later, I do some things and want to save, via Ajax. Part of the process is to grab an array from some side process and set it to my currentModel.Items property and send currentModel to the server.

In my Javascript, however, I did this, instead:

currentModel.items = getData();

I didn't catch it, but in Visual Studio, it will auto lower case the first letter for Javascript properties (it could be a ReSharper thing too). Then, I got the exact error posted by OP when I tried to save because currentModel now has currentModel.items AND currentModel.Items

A simple change from "items" to "Items" fixed the problem.


My problem was that I had a @Url.Action and I had sent through a value for the same property twice


In my case, simply when you compile the code, it runs just fine. But calling one of a static field of a static class that has a dictionary like sample code has, throws the exception.

Sample code

public static AClass
{
    public static Dictionary<string, string> ADict = new Dictionary<string, string>()
        {
            {"test","value1"},{"test","value2"},
        };
}

Explanation ADict has "test" key added twice. So, when you call the static class, it throws the exception.


I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.