2012-07-17 30 views
0

我想在我的控制器中使用UpdateModel從FormCollection中分配一些值。 控制器的樣子:UpdateModel異常

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:可能是堆棧跟蹤將有助於..

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" /> 
} 
+0

你可以發佈* NamedClass *嗎? – VJAI 2012-07-18 03:03:31

+0

發佈...我試圖使用控制器的值提供者編寫UpdateModel(圖片) - 沒有任何改變。 – versus 2012-07-18 04:49:02

回答

0

爲什麼你不能只是做它是這樣的。

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

    return View(); 
} 
+0

,因爲這樣我每次模型更改時都會返回模型更新。 – versus 2012-07-18 06:31:27