UPDATE: tôi bước qua mã MVC nguồn (đặc biệt là DefaultModelBinder
lớp) và đây là những gì tôi thấy:
Lớp xác định chúng tôi đang cố gắng để ràng buộc một bộ sưu tập để nó gọi phương pháp: UpdateCollection(...)
mà tạo ra một bên trong ModelBindingContext
có thuộc tính null
Model
. Sau đó, ngữ cảnh đó được gửi đến phương thức BindComplexModel(...)
để kiểm tra thuộc tính Model
cho null
và tạo một trường hợp mới loại mô hình nếu trường hợp đó xảy ra.
Đó là nguyên nhân khiến giá trị được đặt lại.
Và như vậy, chỉ các giá trị đang đến thông qua dữ liệu chuỗi/truy vấn biểu mẫu/truy vấn được điền, phần còn lại vẫn ở trạng thái ban đầu.
Tôi có thể thực hiện rất ít thay đổi đối với UpdateCollection(...)
để khắc phục vấn đề này.
Dưới đây là phương pháp với những thay đổi của tôi:
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;
}
Nguồn
2009-07-30 19:26:36
có đúng với MVC 3 không? – Vidar
@Vidar Có sợ vậy. – nfplee