Error: An item with the same key has already been added. Where is the problem?
Error: An item with the same key has already been added. Where is the problem?
关于post的方法报错,看不懂,找不到原因。我假设,也许,错误的 somewehre 在视图中,但在哪里无法捕捉到它。
整个项目是here
//Edit view
@model BookRental.Models.IndexViewModel
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div>
<h2>Change Credentials</h2>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.membershipTypeId)
<div class="form-horizontal">
<div class="border rounded">
@*First Name*@
<div class="form-group">
@Html.LabelFor(m => m.fname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.fname, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.fname, "", new { @class = "text-danger" })
</div>
</div>
@*Last Name*@
<div class="form-group">
@Html.LabelFor(m => m.lname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.lname, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.lname, "", new { @class = "text-danger" })
</div>
</div>
@*Birthday*@
<div class="form-group">
@Html.LabelFor(m => m.bdate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.bdate, "{0: MM/dd/yyyy}", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.bdate, "", new { @class = "text-danger" })
</div>
</div>
@*Phone*@
<div class="form-group">
@Html.LabelFor(m => m.phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.phone, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.phone, "", new { @class = "text-danger" })
</div>
</div>
@*Email Adress*@
<div class="form-group">
@Html.LabelFor(m => m.mail, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.mail, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.mail, "", new { @class = "text-danger" })
</div>
</div>
<fieldset disabled>
@*Membership Type*@
<div class="form-group">
@Html.LabelFor(m => m.membershipTypeId, "Membership Type", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.membershipTypeId, new SelectList(Model.MembershipTypes, "membershipTypesIdPK", "name"), new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.membershipTypeId, "", new { @class = "text-danger" })
</div>
</div>
</fieldset>
<br />
<div class="offset-md-2">
<a type="button" href="@Url.Action("Index")" class="btn btn-sm btn-primary">
<span class="text-capitalize">back to profile</span>
</a>
<input type="submit" value="Update Details" class="btn btn-sm btn-success" />
</div>
</div>
</div>
</div>
}
//控制器
//
// POST: /Manage/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IndexViewModel model)
{
using(var db = ApplicationDbContext.Create())
{
if (ModelState.IsValid)
{
var userInDB = db.Users.First(u => u.Id.Equals(model.membershipTypeId));
userInDB.fname = model.fname;
userInDB.lname = model.lname;
userInDB.phone = model.phone;
userInDB.Email = model.mail;
userInDB.bdate = model.bdate;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
model.MembershipTypes = db.MembershipTypes.ToList();
}
}
return View(model);
}
//型号
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
public ICollection<MembershipTypes> MembershipTypes { get; set; }
[Required]
public int membershipTypeId { get; set; }
[Display(Name = "First Name")]
public string fname { get; set; }
[Display(Name = "First Name")]
public string lname { get; set; }
[Display(Name = "Phone")]
public string phone { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Birth Date")]
[DisplayFormat(DataFormatString = "{0:MMM dd yyyy}")]
public DateTime bdate { get; set; }
[Required]
[Display(Name = "Membership Type")]
public string membershipTypeID { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string mail { get; set; }
}
//这是我得到的错误
Server Error in '/' Application.
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +56
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +12948192
System.Collections.Generic.CollectionExtensions.ToDictionaryFast(TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer) +116
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +149
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +176
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1209
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +333
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +343
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4075.0
----------
----------
----------
----------
----------
----------
----------
----------
----------
----------
NOTE:: 顺便说一下,pelase 推荐我强大的资源,比如书籍或视频课程,适合初学者,不是绝对的,用于深入理解 razor 和 mvc 等的原理.. 首选俄语,但英语也适合
https://github.com/TeymurovFuad/BookRental/blob/master/Models/ManageViewModels.cs
编辑:您的 IndexViewModel 中似乎有两个同名的键。
[Required]
public int membershipTypeId { get; set; }
...
[Required]
[Display(Name = "Membership Type")]
public string membershipTypeID { get; set; }
您应该考虑重命名或删除其中之一。
同样在您看来,您有两个使用相同键的表单域; membershipTypeId.
@Html.HiddenFor(m => m.membershipTypeId)
...
@Html.DropDownListFor(m => m.membershipTypeId, new SelectList(Model.MembershipTypes, "membershipTypesIdPK", "name"), new { @class = "form-control" })
尝试移除
@Html.HiddenFor(m => m.membershipTypeId)
关于post的方法报错,看不懂,找不到原因。我假设,也许,错误的 somewehre 在视图中,但在哪里无法捕捉到它。
整个项目是here
//Edit view
@model BookRental.Models.IndexViewModel
@{
ViewBag.Title = "Edit";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div>
<h2>Change Credentials</h2>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.membershipTypeId)
<div class="form-horizontal">
<div class="border rounded">
@*First Name*@
<div class="form-group">
@Html.LabelFor(m => m.fname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.fname, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.fname, "", new { @class = "text-danger" })
</div>
</div>
@*Last Name*@
<div class="form-group">
@Html.LabelFor(m => m.lname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.lname, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.lname, "", new { @class = "text-danger" })
</div>
</div>
@*Birthday*@
<div class="form-group">
@Html.LabelFor(m => m.bdate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.bdate, "{0: MM/dd/yyyy}", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.bdate, "", new { @class = "text-danger" })
</div>
</div>
@*Phone*@
<div class="form-group">
@Html.LabelFor(m => m.phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.phone, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.phone, "", new { @class = "text-danger" })
</div>
</div>
@*Email Adress*@
<div class="form-group">
@Html.LabelFor(m => m.mail, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.mail, new { htmlattributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.mail, "", new { @class = "text-danger" })
</div>
</div>
<fieldset disabled>
@*Membership Type*@
<div class="form-group">
@Html.LabelFor(m => m.membershipTypeId, "Membership Type", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.membershipTypeId, new SelectList(Model.MembershipTypes, "membershipTypesIdPK", "name"), new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.membershipTypeId, "", new { @class = "text-danger" })
</div>
</div>
</fieldset>
<br />
<div class="offset-md-2">
<a type="button" href="@Url.Action("Index")" class="btn btn-sm btn-primary">
<span class="text-capitalize">back to profile</span>
</a>
<input type="submit" value="Update Details" class="btn btn-sm btn-success" />
</div>
</div>
</div>
</div>
}
//控制器
//
// POST: /Manage/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IndexViewModel model)
{
using(var db = ApplicationDbContext.Create())
{
if (ModelState.IsValid)
{
var userInDB = db.Users.First(u => u.Id.Equals(model.membershipTypeId));
userInDB.fname = model.fname;
userInDB.lname = model.lname;
userInDB.phone = model.phone;
userInDB.Email = model.mail;
userInDB.bdate = model.bdate;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
model.MembershipTypes = db.MembershipTypes.ToList();
}
}
return View(model);
}
//型号
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
public ICollection<MembershipTypes> MembershipTypes { get; set; }
[Required]
public int membershipTypeId { get; set; }
[Display(Name = "First Name")]
public string fname { get; set; }
[Display(Name = "First Name")]
public string lname { get; set; }
[Display(Name = "Phone")]
public string phone { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Birth Date")]
[DisplayFormat(DataFormatString = "{0:MMM dd yyyy}")]
public DateTime bdate { get; set; }
[Required]
[Display(Name = "Membership Type")]
public string membershipTypeID { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string mail { get; set; }
}
//这是我得到的错误
Server Error in '/' Application.
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +56
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +12948192
System.Collections.Generic.CollectionExtensions.ToDictionaryFast(TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer) +116
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +149
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +176
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1209
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +333
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +343
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4075.0
----------
----------
----------
----------
----------
----------
----------
----------
----------
----------
NOTE:: 顺便说一下,pelase 推荐我强大的资源,比如书籍或视频课程,适合初学者,不是绝对的,用于深入理解 razor 和 mvc 等的原理.. 首选俄语,但英语也适合
https://github.com/TeymurovFuad/BookRental/blob/master/Models/ManageViewModels.cs
编辑:您的 IndexViewModel 中似乎有两个同名的键。
[Required]
public int membershipTypeId { get; set; }
...
[Required]
[Display(Name = "Membership Type")]
public string membershipTypeID { get; set; }
您应该考虑重命名或删除其中之一。
同样在您看来,您有两个使用相同键的表单域; membershipTypeId.
@Html.HiddenFor(m => m.membershipTypeId)
...
@Html.DropDownListFor(m => m.membershipTypeId, new SelectList(Model.MembershipTypes, "membershipTypesIdPK", "name"), new { @class = "form-control" })
尝试移除
@Html.HiddenFor(m => m.membershipTypeId)