Fuad Teymurov
Fuad Teymurov

Reputation: 73

Error: An item with the same key has already been added. Where is the problem?

On post method I get an error, can not understan, can not find the reason. I assume, maybe, mistake somewehre in view, but where can not catch it.

Whole project is 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>
}

//Controller

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

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

//This is an error i get

    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:: By the way, pelase recommend me strong source, like a book or video lessons, for beginners, not absolute, for deep understanding principles of razor and mvc etc.. Preferred in russian, but english also will suit

Upvotes: 0

Views: 2474

Answers (1)

Jerdine Sabio
Jerdine Sabio

Reputation: 6130

https://github.com/TeymurovFuad/BookRental/blob/master/Models/ManageViewModels.cs

EDIT: It seems that in your IndexViewModel you have two keys of the same name.

[Required]
public int membershipTypeId { get; set; }
...
[Required]
[Display(Name = "Membership Type")]
public string membershipTypeID { get; set; }

You should consider renaming or removing one of them.

Also in your view, you have two form fields that uses the same key; membershipTypeId.

@Html.HiddenFor(m => m.membershipTypeId)

...

@Html.DropDownListFor(m => m.membershipTypeId, new SelectList(Model.MembershipTypes, "membershipTypesIdPK", "name"), new { @class = "form-control" })

Try removing

@Html.HiddenFor(m => m.membershipTypeId)

Upvotes: 1

Related Questions