asp.net-mvc 已添加具有相同键的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5648060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:07:23  来源:igfitidea点击:

An item with the same key has already been added

asp.net-mvc

提问by user650922

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

[ArgumentException:已添加具有相同键的项目。]
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比较器) +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 结果) +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>
      <%} %>

回答by Aliostad

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

很可能,您的模型两次包含相同的属性。也许您正在使用new隐藏基本属性。

Solution is to override the property or use another name.

解决方案是覆盖该属性或使用其他名称。

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

如果您分享您的模型,我们将能够详细说明。

回答by atulpatel.mca

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.

我遇到了同样的问题,这就是我解决它的方法。我的 ViewModel 中有一个同名的重复属性。一个属性在 BaseViewModel 中,另一个在派生模型中。

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.

现在它工作正常。

回答by Hal

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;}

回答by CuriousBenjamin

I had 2 model properties like this

我有 2 个这样的模型属性

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

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

奇怪的是它为这两个抛出了这个错误哈哈..

回答by Jason Goemaat

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 Notesfield on the page while my C# object was expecting lower-case notes. A more descriptive error would sure be nice.

我的问题不在我的 C# 模型中,而是在我使用 AJAX 发布的 javascript 对象中。我正在使用 Angular 进行绑定,并且Notes页面上有一个大写的字段,而我的 C# 对象需要小写的notes. 更具描述性的错误肯定会很好。

C#:

C#:

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

Angular/Javascript:

角度/Javascript:

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

回答by Mina Gabriel

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

我遇到了同样的问题,我正在foreach遍历我的对象并将结果添加到 a 中,Dictionary<string, string>并且我在数据库中的键中出现了“重复”

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

        }

item.xhad a duplicate value

item.x有重复值

回答by user650922

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

我找到了答案。这是因为变量。像 int a 和 string a。有两个同名的变量。

回答by Ahmet Remzi EKMEKCI

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"},
        };
}

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

说明ADict 两次添加了“test”键。因此,当您调用静态类时,它会抛出异常。

回答by bvoleti

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.zipand 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.

这是我为找出被添加两次的密钥所做的工作。我从http://referencesource.microsoft.com/DotNetReferenceSource.zip下载了源代码并设置 VS 来调试框架源。在 VS 中打开 Dictionary.cs 运行项目,页面加载后,在该行添加调试ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);并能够看到“键”值。我意识到在 JSON 中变量的一个字母是大写的,但在我的模型中它是小写的。我修复了模型,现在相同的代码可以工作。

回答by Jeremy Cook

I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an IndexAttributelike 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.

我在 MVC 5 和 Visual Studio Express 2013 中遇到了这个问题。我有两个IndexAttribute类似下面的属性。注释掉其中之一并重新编译会导致使用视图搭建 MVC 5 控制器,成功使用实体框架。神秘的是,当我取消对属性的注释,重新编译并再次尝试时,脚手架运行得很好。

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

也许底层实体数据模型或“某物”被缓存/损坏,删除和重新添加IndexAttribute只是触发了该“某物”的重建。

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

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