Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An item with the same key has already been added

Tags:

asp.net-mvc

Most likely, you have model which contains the same property twice. Perhaps you are using new to hide the base property.

Solution is to override the property or use another name.

If you share your model, we would be able to elaborate more.


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 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">