2015-10-23 3 views
1

При попытке отправить форму с загрузкой файла/несколькими файлами/полями/флажком для заполнения я получаю вышеуказанную ошибку. Я использовал различные ресурсы для SO, но не смог определить проблему. Вот моя трассировка стеки ниже:Элемент с тем же ключом уже добавлен ... ASP.NET MVC4

[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) +10925834 
    System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) +10 
    System.Collections.Generic.CollectionExtensions.ToDictionaryFast(TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer) +209 
    System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +201 
    System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +387 
    System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +180 
    System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +106 
    System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2541 
    System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +633 
    System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +494 
    System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199 
    System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680 
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 
    System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94 
    System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559 
    System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 
    System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105 
    System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588 
    System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 
    System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139 
    System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484 
    System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50 
    System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 
    System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446 
    System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 

я правильно прошел через мою модель и мой ViewModel, я не нашел какое-либо дублирования в свойствах. Вот мой ViewModel:

public class ArticlesViewModel 
{ 
    public ArticlesViewModel() 
    { 
     Teams = new List<TeamVM>();    
    } 

    public string gameName { get; set; } 

    public List<TeamVM> Teams { get; set; } 

    [Required] 
    [DisplayName("Article Content")] 
    public string articleContent { get; set; } 

    public System.DateTime date { get; set; } 

    [Required] 
    [DisplayName("Article Title")] 
    public string articleTitle { get; set; } 

    [ValidateFile] 
    [Display(Name = "FeaturedImage")] 
    public HttpPostedFileBase featuredImage { get; set; } 

    [ValidateFile] 
    [Display(Name = "Picture Gallery Image(s)")]  
    public IEnumerable<HttpPostedFileBase> picturePath { get; set; } 

    // properties for the articles, game, gallery and teams respectively    
    public gallery mgallery { get; set; } 
    public TeamVM teams { get; set; } 
} 

А вот действие контроллера для ViewModel:

namespace TeamBuildingCompetition.Areas.Admin.Controllers 
{ 
    public class ArticlesController : BaseAdminController 
    { 
     // GET: Admin/Articles 

     TBCDBEntities db; 

     public ArticlesController() 
     { 
      db = new TBCDBEntities(); 
     } 

     [HttpGet] 
     public ActionResult Index() 
     { 
      ArticlesViewModel model = new ArticlesViewModel(); 
      var teamList = (from p in db.teams 
         select new TeamVM() 
         { 
          teamID = p.teamID, 
          TeamName = p.teamName, 
          IsSelected = p.IsSelected 
         }); 
      model.Teams = teamList.ToList(); 

      ViewBag.gameList = new SelectList(db.games, "gameID", "gameName");   
      return View(model); 
     } 

     [HttpPost] 
     public ActionResult Create(ArticlesViewModel model) 
     {    
      try 
      { 
       // Get the featured file name 
       string featuredFileName = Path.GetFileName(model.featuredImage.FileName); 

       // Get the featured file path 
       string path = Path.Combine(Server.MapPath("~/Content/Upload"), featuredFileName); 

       // Get the path that will be saved into the database 
       string imgDBPath = "~/Content/Upload/" + featuredFileName.ToString(); 

       // Save the featured images to the folder 
       model.featuredImage.SaveAs(path);    

       // Declare the picture gallery file path names 
       var getFileNames = ""; 
       var getGalleryPath = ""; 
       var getGalleryImgPath = "";  

       // Iterate through each file in the collection     
       foreach (var item in model.picturePath) 
       {      
        getFileNames = Path.GetFileName(item.FileName); // Get the file names 
        getGalleryPath = Path.Combine(Server.MapPath("~/Content/Upload"), getFileNames); // Get the file paths 
        getGalleryImgPath = "~/Content/Upload/" + getFileNames.ToString(); // Get the file path to be stored in the database      

        item.SaveAs(getGalleryPath); // Save the each file in the upload directory 
       } 

       // Map article properties with values 
       article objArticle = new article 
       { 
        featuredImage = imgDBPath, 
        articleTitle = model.articleTitle, 
        articleContent = model.gameName, 
        date = DateTime.Now, 
        lastupdated = DateTime.Now 
       }; 

       // Map gallery properties with values 
       gallery objGallery = new gallery 
       {      
        gameID = model.mgallery.gameID, 
        teamID = model.teams.teamID, 
        picturePath = model.picturePath.ToString() 
       }; 

       // Insert the article/gallery picture into the database 
       objBs.articleBs.Insert(objArticle); 
       objBs.galleryBs.Insert(objGallery); 

       TempData["Msg"] = "Created Successfully!"; 
       return RedirectToAction("Index"); 

      } 
      catch (DbEntityValidationException dbEx) 
      { 
       var sb = new StringBuilder(); 
       foreach (var validationErrors in dbEx.EntityValidationErrors) 
       { 
        foreach (var validationError in validationErrors.ValidationErrors) 
        { 
         sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'", 
         validationErrors.Entry.Entity.GetType().FullName, 
         validationError.PropertyName, 
         validationError.ErrorMessage)); 
        } 
       } 

       //throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx); 
       TempData["Msg"] = sb.ToString(); 
       return RedirectToAction("Index"); 
      }    
     } 
    } 
} 

И всякий раз, когда я удалить ArticlesViewModel model из public ActionResult create(ArticlesViewModel model) контроллера, я получаю нулевую ссылочную ошибку.

+4

Публичный список Команды {get; задавать; } и публичные команды TeamVM {get; задавать; } выглядит подозрительно. –

ответ

8

Вы оба

public List<TeamVM> Teams { get; set; } 

и

public TeamVM teams { get; set; } 

Хотя это справедливо C#, у вас есть два свойства с тем же именем (если не принимать во внимание случай).

Просто измените свои имена.

+0

Спасибо! Это помогло мне в моей ситуации – Ekaterina

Смежные вопросы