已经添加了具有相同键的项目... ASP.NET MVC4

时间:2015-10-23 15:34:25

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

在尝试提交带有文件上传/多个文件上传/表单字段/复选框的表单时,我收到上述错误。我在SO上经历了各种资源但无法确定问题。这是我的堆栈跟踪:

[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)时,都会出现空引用错误。

1 个答案:

答案 0 :(得分:8)

你们俩都有

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

public TeamVM teams { get; set; }

虽然这是有效的C#,但您有两个具有相同名称的属性(如果您不考虑案例)。

只需更改名称即可。

相关问题