与自定义属性getter的模型绑定错误

asa*_*yer 4 c# asp.net-mvc-3

当我使用try尝试使用这两个属性绑定模型时,我在模型绑定期间遇到错误:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误:

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: 
Run Code Online (Sandbox Code Playgroud)

如果我将属性更改为基本自动属性:

    public IEnumerable<Claimant> Drivers { get; set; }
    public IEnumerable<Property> Vehicles { get; set; }
Run Code Online (Sandbox Code Playgroud)

一切正常.

当setter与auto属性setter相同时,为什么模型绑定会出现问题?

编辑 - 通过默认模型绑定源读取最终会引导您到达第一行调用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

试试这样:

get 
{
    return _drivers ?? new List<Claimant>();
}
Run Code Online (Sandbox Code Playgroud)

  • 属性返回的集合必须是动态的,而不是静态的只读数组,因为模型绑定器会尝试调整它的大小. (6认同)

D S*_*ley 5

IIRC Enumerable.Empty<T>是一个静态的只读枚举,用于传递一个空的存储不可知的可枚举方法.它并不意味着用作空集合的"起点".这可能是你收到错误的原因.

选择存储机制(例如List<T>)并将其用作支持字段的类型.然后,您可以初始化它

  1. 在类定义中,
  2. 在构造函数中,或
  3. 起初得到:

例子:

private List<Claimant> _drivers = new List<Claimamt>();  // Option 1

public MyModel()
{
    _drivers = new List<Claimant>();   // Option 2
}

public IEnumerable<Claimant> Drivers
{
    get
    {
        return _drivers ?? (_drivers = new List<Claimant>()); // Option 3
    }
    set
    {
        _drivers = value;
    }
}
Run Code Online (Sandbox Code Playgroud)