当前位置: 首页>>代码示例>>C#>>正文


C# ModelBindingContext类代码示例

本文整理汇总了C#中ModelBindingContext的典型用法代码示例。如果您正苦于以下问题:C# ModelBindingContext类的具体用法?C# ModelBindingContext怎么用?C# ModelBindingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ModelBindingContext类属于命名空间,在下文中一共展示了ModelBindingContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ModelMetadataProvider_UsesPredicateOnType

        public void ModelMetadataProvider_UsesPredicateOnType()
        {
            // Arrange
            var type = typeof(User);

            var provider = CreateProvider();
            var context = new ModelBindingContext();

            var expected = new[] { "IsAdmin", "UserName" };

            // Act
            var metadata = provider.GetMetadataForType(type);

            // Assert
            var predicate = metadata.PropertyBindingPredicateProvider.PropertyFilter;

            var matched = new HashSet<string>();
            foreach (var property in metadata.Properties)
            {
                if (predicate(context, property.PropertyName))
                {
                    matched.Add(property.PropertyName);
                }
            }

            Assert.Equal<string>(expected, matched);
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:27,代码来源:ModelMetadataProviderTest.cs

示例2: GetBinder

 public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
 {
     return (from provider in _providers
             let binder = provider.GetBinder(actionContext, bindingContext)
             where binder != null
             select binder).FirstOrDefault();
 }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:7,代码来源:BinaryDataModelBinderProvider.cs

示例3: BindModel

        public async Task BindModel()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = metadataProvider.GetMetadataForType(typeof(IDictionary<int, string>)),
                ModelName = "someName",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "someName[0]", new KeyValuePair<int, string>(42, "forty-two") },
                    { "someName[1]", new KeyValuePair<int, string>(84, "eighty-four") }
                },
                OperationBindingContext = new OperationBindingContext
                {
                    ModelBinder = CreateKvpBinder(),
                    MetadataProvider = metadataProvider
                }
            };
            var binder = new DictionaryModelBinder<int, string>();

            // Act
            var retVal = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotNull(retVal);

            var dictionary = Assert.IsAssignableFrom<IDictionary<int, string>>(retVal.Model);
            Assert.NotNull(dictionary);
            Assert.Equal(2, dictionary.Count);
            Assert.Equal("forty-two", dictionary[42]);
            Assert.Equal("eighty-four", dictionary[84]);
        }
开发者ID:AndersBillLinden,项目名称:Mvc,代码行数:33,代码来源:DictionaryModelBinderTest.cs

示例4: BindModel

        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // case 1: there was no <input ... /> element containing this data
            if (valueResult == null)
            {
                return null;
            }

            string value = valueResult.AttemptedValue;

            // case 2: there was an <input ... /> element but it was left blank
            if (String.IsNullOrEmpty(value))
            {
                return null;
            }

            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
            // then we need to remove these quotes put in place by the ToString() method.
            string realValue = value.Replace("\"", String.Empty);
            return Convert.FromBase64String(realValue);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:28,代码来源:ByteArrayModelBinder.cs

示例5: TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue

        public void TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue()
        {
            // Arrange
            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
                ModelName = "someName",
                ModelState = new ModelStateDictionary(),
                ValueProvider = new SimpleHttpValueProvider()
            };
            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true });

            mockIntBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>
                {
                    Assert.Equal("someName.key", mbc.ModelName);
                    return true;
                });

            // Act
            int model;
            bool retVal = context.TryBindStrongModel(bindingContext, "key", new EmptyModelMetadataProvider(), out model);

            // Assert
            Assert.True(retVal);
            Assert.Equal(default(int), model);
            Assert.Single(bindingContext.ValidationNode.ChildNodes);
            Assert.Empty(bindingContext.ModelState);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:32,代码来源:KeyValuePairModelBinderUtilTest.cs

示例6: BindModel

            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
            {
                ModelBindingHelper.ValidateBindingContext(bindingContext);
                ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

                // case 1: there was no <input ... /> element containing this data
                if (valueProviderResult == null)
                {
                    return false;
                }

                string base64String = (string)valueProviderResult.ConvertTo(typeof(string));

                // case 2: there was an <input ... /> element but it was left blank
                if (String.IsNullOrEmpty(base64String))
                {
                    return false;
                }

                // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
                // then we need to remove these quotes put in place by the ToString() method.
                string realValue = base64String.Replace("\"", String.Empty);
                try
                {
                    bindingContext.Model = ConvertByteArray(Convert.FromBase64String(realValue));
                    return true;
                }
                catch
                {
                    // corrupt data - just ignore
                    return false;
                }
            }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:33,代码来源:BinaryDataModelBinderProvider.cs

示例7: BindModel_MissingValue_ReturnsTrue

        public void BindModel_MissingValue_ReturnsTrue()
        {
            // Arrange
            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),
                ModelName = "someName",
                ValueProvider = new SimpleHttpValueProvider()
            };
            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.ServiceResolver.SetService(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true });

            mockIntBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>
                {
                    mbc.Model = 42;
                    return true;
                });
            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();

            // Act
            bool retVal = binder.BindModel(context, bindingContext);

            // Assert
            Assert.True(retVal);
            Assert.Null(bindingContext.Model);
            Assert.Equal(new[] { "someName.key" }, bindingContext.ValidationNode.ChildNodes.Select(n => n.ModelStateKey).ToArray());
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:30,代码来源:KeyValuePairModelBinderTest.cs

示例8: BindModel

        public void BindModel()
        {
            // Arrange
            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));

            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),
                ModelName = "someName",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "someName[0]", "42" },
                    { "someName[1]", "84" }
                }
            };
            mockIntBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>
                {
                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);
                    return true;
                });

            // Act
            bool retVal = new ArrayModelBinder<int>().BindModel(context, bindingContext);

            // Assert
            Assert.True(retVal);

            int[] array = bindingContext.Model as int[];
            Assert.Equal(new[] { 42, 84 }, array);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:34,代码来源:ArrayModelBinderTest.cs

示例9: BindModel

        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            bool boundSuccessfully = TryBind(actionContext, newBindingContext);
            if (!boundSuccessfully && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, modelName: String.Empty);
                boundSuccessfully = TryBind(actionContext, newBindingContext);
            }

            if (!boundSuccessfully)
            {
                return false; // something went wrong
            }

            // run validation and return the model
            // If we fell back to an empty prefix above and are dealing with simple types,
            // propagate the non-blank model name through for user clarity in validation errors.
            // Complex types will reveal their individual properties as model names and do not require this.
            if (!newBindingContext.ModelMetadata.IsComplexType && String.IsNullOrEmpty(newBindingContext.ModelName))
            {
                newBindingContext.ValidationNode = new Validation.ModelValidationNode(newBindingContext.ModelMetadata, bindingContext.ModelName);
            }

            newBindingContext.ValidationNode.Validate(actionContext, null /* parentNode */);
            bindingContext.Model = newBindingContext.Model;
            return true;
        }
开发者ID:reza899,项目名称:aspnetwebstack,代码行数:31,代码来源:CompositeModelBinder.cs

示例10: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            var theFile = controllerContext.HttpContext.Request.Files[bindingContext.ModelName];

            // case 1: there was no <input type="file" ... /> element in the post
            if (theFile == null)
            {
                return null;
            }

            // case 2: there was an <input type="file" ... /> element in the post, but it was left blank
            if (theFile.ContentLength == 0 && String.IsNullOrEmpty(theFile.FileName))
            {
                return null;
            }

            // case 3: the file was posted
            return theFile;
        }
开发者ID:mhinze,项目名称:msmvc,代码行数:28,代码来源:HttpPostedFileBaseModelBinder.cs

示例11: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(ComplexModelDto), false /* allowNullModel */);

            ComplexModelDto dto = (ComplexModelDto)bindingContext.Model;
            foreach (ModelMetadata propertyMetadata in dto.PropertyMetadata)
            {
                ModelBindingContext propertyBindingContext = new ModelBindingContext(bindingContext)
                {
                    ModelMetadata = propertyMetadata,
                    ModelName = ModelBindingHelper.CreatePropertyModelName(bindingContext.ModelName, propertyMetadata.PropertyName)
                };

                // bind and propagate the values
                IModelBinder propertyBinder;
                if (actionContext.TryGetBinder(propertyBindingContext, out propertyBinder))
                {
                    if (propertyBinder.BindModel(actionContext, propertyBindingContext))
                    {
                        dto.Results[propertyMetadata] = new ComplexModelDtoResult(propertyBindingContext.Model, propertyBindingContext.ValidationNode);
                    }
                    else
                    {
                        dto.Results[propertyMetadata] = null;
                    }
                }
            }

            return true;
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:30,代码来源:ComplexModelDtoModelBinder.cs

示例12: GetBinder

        public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingHelper.ValidateBindingContext(bindingContext);

            Type[] typeArguments = null;
            if (ModelType.IsInterface)
            {
                Type matchingClosedInterface = TypeHelper.ExtractGenericInterface(bindingContext.ModelType, ModelType);
                if (matchingClosedInterface != null)
                {
                    typeArguments = matchingClosedInterface.GetGenericArguments();
                }
            }
            else
            {
                typeArguments = TypeHelper.GetTypeArgumentsIfMatch(bindingContext.ModelType, ModelType);
            }

            if (typeArguments != null)
            {
                if (SuppressPrefixCheck || bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
                {
                    return _modelBinderFactory(typeArguments);
                }
            }

            return null;
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:28,代码来源:GenericModelBinderProvider.cs

示例13: BindModel

        public void BindModel()
        {
            // Arrange
            Mock<IModelBinder> mockDtoBinder = new Mock<IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = GetMetadataForObject(new Person()),
                ModelName = "someName"
            };
            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(ComplexModelDto), mockDtoBinder.Object) { SuppressPrefixCheck = true });

            mockDtoBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext cc, ModelBindingContext mbc2) =>
                {
                    return true; // just return the DTO unchanged
                });

            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };
            mockTestableBinder.Setup(o => o.EnsureModelPublic(context, bindingContext)).Verifiable();
            mockTestableBinder.Setup(o => o.GetMetadataForPropertiesPublic(context, bindingContext)).Returns(new ModelMetadata[0]).Verifiable();
            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;
            testableBinder.MetadataProvider = new DataAnnotationsModelMetadataProvider();

            // Act
            bool retValue = testableBinder.BindModel(context, bindingContext);

            // Assert
            Assert.True(retValue);
            Assert.IsType<Person>(bindingContext.Model);
            Assert.True(bindingContext.ValidationNode.ValidateAllProperties);
            mockTestableBinder.Verify();
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:34,代码来源:MutableObjectModelBinderTest.cs

示例14: ModelNameProperty

        public void ModelNameProperty()
        {
            // Arrange
            ModelBindingContext bindingContext = new ModelBindingContext();

            // Act & assert
            MemberHelper.TestStringProperty(bindingContext, "ModelName", String.Empty);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:8,代码来源:ModelBindingContextTest.cs

示例15: BindModelAsync

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult == ValueProviderResult.None)
            {
                // no entry
                return TaskCache.CompletedTask;
            }

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            try
            {
                if (string.IsNullOrEmpty(valueProviderResult.Values))
                {
                    if (bindingContext.ModelType == typeof(decimal?))
                    {
                        decimal? defaultValue = null;
                        bindingContext.Result = ModelBindingResult.Success(defaultValue);
                        return TaskCache.CompletedTask;
                    }
                    else
                    {
                        decimal defaultValue = 0.0M;
                        bindingContext.Result = ModelBindingResult.Success(defaultValue);
                        return TaskCache.CompletedTask;
                    }
                }

                decimal model = Convert.ToDecimal(
                        valueProviderResult.Values,
                        CultureInfo.InvariantCulture);

                bindingContext.Result = ModelBindingResult.Success(model);
                return TaskCache.CompletedTask;
            }
            catch (Exception exception)
            {
                bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    exception,
                    bindingContext.ModelMetadata);

                //customized error message
                //string displayName = bindingContext.ModelMetadata.DisplayName ?? bindingContext.ModelName;
                //bindingContext.ModelState.TryAddModelError(bindingContext.ModelName,
                //    string.Format("not decimal input:{0}", displayName));

                // Were able to find a converter for the type but conversion failed.
                return TaskCache.CompletedTask;
            }
        }
开发者ID:shimitei,项目名称:ConvertModelBinder,代码行数:57,代码来源:ConvertModelBinder.cs


注:本文中的ModelBindingContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。