Пример #1
0
        public void GetZeroBasedIndexes()
        {
            // Act
            string[] indexes = CollectionModelBinderUtil.GetZeroBasedIndexes().Take(5).ToArray();

            // Assert
            Assert.Equal(new[] { "0", "1", "2", "3", "4" }, indexes);
        }
Пример #2
0
        internal static List <TElement> BindComplexCollectionFromIndexes(
            HttpActionContext actionContext,
            ModelBindingContext bindingContext,
            IEnumerable <string> indexNames
            )
        {
            bool indexNamesIsFinite;

            if (indexNames != null)
            {
                indexNamesIsFinite = true;
            }
            else
            {
                indexNamesIsFinite = false;
                indexNames         = CollectionModelBinderUtil.GetZeroBasedIndexes();
            }

            List <TElement> boundCollection = new List <TElement>();

            foreach (string indexName in indexNames)
            {
                string fullChildName = ModelBindingHelper.CreateIndexModelName(
                    bindingContext.ModelName,
                    indexName
                    );
                ModelBindingContext childBindingContext = new ModelBindingContext(bindingContext)
                {
                    ModelMetadata = actionContext
                                    .GetMetadataProvider()
                                    .GetMetadataForType(null, typeof(TElement)),
                    ModelName = fullChildName
                };

                bool   didBind    = false;
                object boundValue = null;
                if (actionContext.Bind(childBindingContext))
                {
                    didBind    = true;
                    boundValue = childBindingContext.Model;

                    // merge validation up
                    bindingContext.ValidationNode.ChildNodes.Add(
                        childBindingContext.ValidationNode
                        );
                }

                // infinite size collection stops on first bind failure
                if (!didBind && !indexNamesIsFinite)
                {
                    break;
                }

                boundCollection.Add(ModelBindingHelper.CastOrDefault <TElement>(boundValue));
            }

            return(boundCollection);
        }