// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
///
/// implementation for binding array values.
///
/// Type of elements in the array.
public class ArrayModelBinder : CollectionModelBinder
{
///
public override Task BindModelAsync([NotNull] ModelBindingContext bindingContext)
{
if (bindingContext.ModelMetadata.IsReadOnly)
{
return Task.FromResult(null);
}
return base.BindModelAsync(bindingContext);
}
///
public override bool CanCreateInstance(Type targetType)
{
return targetType == typeof(TElement[]);
}
///
protected override object CreateEmptyCollection(Type targetType)
{
Debug.Assert(targetType == typeof(TElement[]), "GenericModelBinder only creates this binder for arrays.");
return new TElement[0];
}
///
protected override object ConvertToCollectionType(Type targetType, IEnumerable collection)
{
Debug.Assert(targetType == typeof(TElement[]), "GenericModelBinder only creates this binder for arrays.");
// If non-null, collection is a List, never already a TElement[].
return collection?.ToArray();
}
///
protected override void CopyToModel([NotNull] object target, IEnumerable sourceCollection)
{
// Do not attempt to copy values into an array because an array's length is immutable. This choice is also
// consistent with MutableObjectModelBinder's handling of a read-only array property.
}
}
}