更新:
mvc ソース コード (特にDefaultModelBinder
クラス) を調べたところ、次のような結果が得られました。
クラスは、コレクションをバインドしようとしていると判断し、メソッドを呼び出します:プロパティを持つUpdateCollection(...)
インナーを作成します。その後、そのコンテキストがメソッドに送信され、プロパティがチェックされ、モデル タイプの新しいインスタンスが作成されます (該当する場合)。ModelBindingContext
null
Model
BindComplexModel(...)
Model
null
それが値がリセットされる原因です。
そのため、フォーム/クエリ文字列/ルート データからの値のみが入力され、残りは初期化された状態のままです。
UpdateCollection(...)
この問題を修正するために、ほとんど変更を加えることができませんでした。
ここに私の変更を加えた方法があります:
internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) {
IModelBinder elementBinder = Binders.GetBinder(elementType);
// build up a list of items from the request
List<object> modelList = new List<object>();
for (int currentIndex = 0; ; currentIndex++) {
string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, subIndexKey)) {
// we ran out of elements to pull
break;
}
// **********************************************************
// The DefaultModelBinder shouldn't always create a new
// instance of elementType in the collection we are updating here.
// If an instance already exists, then we should update it, not create a new one.
// **********************************************************
IList containerModel = bindingContext.Model as IList;
object elementModel = null;
if (containerModel != null && currentIndex < containerModel.Count)
{
elementModel = containerModel[currentIndex];
}
//*****************************************************
ModelBindingContext innerContext = new ModelBindingContext() {
Model = elementModel, // assign the Model property
ModelName = subIndexKey,
ModelState = bindingContext.ModelState,
ModelType = elementType,
PropertyFilter = bindingContext.PropertyFilter,
ValueProvider = bindingContext.ValueProvider
};
object thisElement = elementBinder.BindModel(controllerContext, innerContext);
// we need to merge model errors up
VerifyValueUsability(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);
modelList.Add(thisElement);
}
// if there weren't any elements at all in the request, just return
if (modelList.Count == 0) {
return null;
}
// replace the original collection
object collection = bindingContext.Model;
CollectionHelpers.ReplaceCollection(elementType, collection, modelList);
return collection;
}