UpdateModel异常

时间:2012-07-17 17:36:20

标签: asp.net-mvc-3 updatemodel

我正在尝试使用UpdateModel从我的控制器中的FormCollection中分配一些值。 控制器看起来像:

public ActionResult EditValues(int id, FormCollection collection)
{
   NamedClass picture = PictureProvider.GetById(id);
   try
   {
      if(ModelState.IsValid)
        {
            UpdateModel(picture, collection);
        }
   }
   catch {}
}

并在字符串UpdateModel(picture, collection);我有一个ArgumentException,说“已经添加了具有相同键的元素”,仅此而已...... “集合”与“图片”具有相同的字段。我不是要向“集合”添加任何可能导致此类异常的内容。试图手动为图片的字段赋值 - 好的。 有没有人见过这样的伎俩?先感谢您! UPD:可能是StackTrace会有所帮助..

System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   System.Web.Mvc.ModelBindingContext.get_PropertyMetadata()
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
   System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
   System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, IValueProvider valueProvider)

Namedclass是:

public class NamedClass
    {
        [Key]
        public virtual int id {get; set;}
        public virtual string username {get; set;}
    }

和提供值的视图是:

@model project.Models.NamedClass
@using (Html.BeginForm("EditValues", "PicController", FormMethod.Post))
{
    @Html.HiddenFor(m=>m.id)
    <div class="display-label">@Html.LabelFor(model=>model.username)</div>
    <div class="display-field">
        @Html.EditorFor(model => model.username)
    </div>
    <input type="submit" value="save" />
}

1 个答案:

答案 0 :(得分:0)

为什么你不能这样做呢。

public ActionResult EditValues(NamedClass model)
{
  if(ModelState.IsValid)
  {
     .. save to db
  }

  return View();
}
相关问题