模型綁定過程中我也得到一個錯誤,當我使用嘗試使用這兩個屬性的模型綁定:模型綁定錯誤
private IEnumerable<Claimant> _drivers;
public IEnumerable<Claimant> Drivers
{
get
{
return _drivers ?? Enumerable.Empty<Claimant>();
}
set
{
_drivers = value;
}
}
private IEnumerable<Property> _vehicles;
public IEnumerable<Property> Vehicles
{
get
{
return _vehicles ?? Enumerable.Empty<Property>();
}
set
{
_vehicles = value;
}
}
錯誤:
System.Reflection.TargetInvocationException was unhandled by user code
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
<snip>
InnerException: System.NotSupportedException
Message=Collection is read-only.
Source=mscorlib
StackTrace:
at System.SZArrayHelper.Clear[T]()
at System.Web.Mvc.DefaultModelBinder.CollectionHelpers
.ReplaceCollectionImpl[T](ICollection`1 collection, IEnumerable newContents)
InnerException:
如果我將屬性更改爲基本自動屬性:
public IEnumerable<Claimant> Drivers { get; set; }
public IEnumerable<Property> Vehicles { get; set; }
一切工作正常。
爲什麼模型綁定在setter與auto屬性設置器相同時會出現問題?
編輯 - 通過default model binder source閱讀最終會導致你這一點,其中,第一行是調用Clear()
對財產,所以當我回到了Empty<T>
這顯然是行不通的。
private static void ReplaceCollectionImpl<T>(ICollection<T> collection, IEnumerable newContents)
{
collection.Clear();
if (newContents != null)
{
foreach (object item in newContents)
{
// if the item was not a T, some conversion failed. the error message will be propagated,
// but in the meanwhile we need to make a placeholder element in the array.
T castItem = (item is T) ? (T)item : default(T);
collection.Add(castItem);
}
}
}
這糾正錯誤,它只是整個事情覺得奇怪,我。我想我將不得不深入到默認的活頁夾源代碼中,看看它在這裏做了什麼。 – asawyer
屬性返回的集合必須是動態的,而不是靜態只讀數組,因爲模型聯編程序會嘗試調整其大小。 –
是的就是這樣。再次感謝。 – asawyer