0

我正在尝试使用 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)

命名类是:

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" />
}
4

1 回答 1

0

你为什么不能这样。

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

  return View();
}
于 2012-07-18T04:58:03.303 回答