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


C# IModelBinder类代码示例

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


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

示例1: TryGetBinder

        /// <summary>
        /// Gets the <see cref="ModelBindingContext"/> for this <see cref="HttpActionContext"/>.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <param name="binder">When this method returns, the value associated with the specified binding context, if the context is found; otherwise, the default value for the type of the value parameter.</param>
        /// <returns><c>true</c> if <see cref="ModelBindingContext"/> was present; otherwise <c>false</c>.</returns>
        public static bool TryGetBinder(this HttpActionContext actionContext, ModelBindingContext bindingContext, out IModelBinder binder)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

            if (bindingContext == null)
            {
                throw Error.ArgumentNull("bindingContext");
            }

            binder = null;
            ModelBinderProvider providerFromAttr;
            if (ModelBindingHelper.TryGetProviderFromAttributes(bindingContext.ModelType, out providerFromAttr))
            {
                binder = providerFromAttr.GetBinder(actionContext, bindingContext);
            }
            else
            {
                binder = actionContext.ControllerContext.Configuration.Services.GetModelBinderProviders()
                    .Select(p => p.GetBinder(actionContext, bindingContext))
                    .Where(b => b != null)
                    .FirstOrDefault();
            }

            return binder != null;
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:35,代码来源:HttpActionContextExtensions.cs

示例2: AddElement

        public ElementBinding AddElement(Type elementType, IModelBinder binder)
        {
            var binding = new ElementBinding(_elements.Count, elementType, binder);
            _elements.Add(binding);

            return binding;
        }
开发者ID:nieve,项目名称:FubuRESTInnovation,代码行数:7,代码来源:PropertyBindingReport.cs

示例3: GetPropertyValue

        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            // Check for existence of type discriminator field
            string typeDiscrimKey = CreateSubPropertyName(bindingContext.ModelName, "_TYPEDISC_");
            ValueProviderResult vpDiscrim = bindingContext.ValueProvider.GetValue(typeDiscrimKey);
            if (vpDiscrim != null)
            {
                // check for attribute on property specifying the requested type name is allowed
                string typeName = (string)vpDiscrim.ConvertTo(typeof(string));
                var attr = propertyDescriptor.Attributes.OfType<AllowedSubtypesAttribute>().FirstOrDefault();
                if (attr != null && attr.AllowedSubtypeNames.Contains(typeName))
                {
                    // check if the requested type is different from the property type, but assignable to it
                    Type propType = Type.GetType(typeName);
                    if (propType != propertyDescriptor.PropertyType && propertyDescriptor.PropertyType.IsAssignableFrom(propType))
                    {
                        // substitute type of property for specified type
                        IModelBinder newPropertyBinder = Binders.GetBinder(propType);
                        var propertyMetadata =
                            ModelMetadataProviders.Current.GetMetadataForType(() => null, propType);
                        ModelBindingContext newBindingContext = new ModelBindingContext()
                        {
                            ModelMetadata = propertyMetadata,
                            ModelName = bindingContext.ModelName,
                            ModelState = bindingContext.ModelState,
                            ValueProvider = bindingContext.ValueProvider
                        };

                        return base.GetPropertyValue(controllerContext, newBindingContext, propertyDescriptor, newPropertyBinder);
                    }
                }
            }
            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
开发者ID:jamesej,项目名称:lynicon,代码行数:34,代码来源:LyniconBinder.cs

示例4: ChoseModelBinder

 public void ChoseModelBinder(Type modelType, IModelBinder binder)
 {
     _report.AddBindingDetail(new ModelBinderSelection{
         ModelType = modelType,
         BinderType = binder.GetType()
     });
 }
开发者ID:jemacom,项目名称:fubumvc,代码行数:7,代码来源:RecordingBindingLogger.cs

示例5: BindParameter

        /// <summary>
        /// Register that the given parameter type on an Action is to be bound using the model binder.
        /// </summary>
        /// <param name="configuration">configuration to be updated.</param>
        /// <param name="type">parameter type that binder is applied to</param>
        /// <param name="binder">a model binder</param>
        public static void BindParameter(this HttpConfiguration configuration, Type type, IModelBinder binder)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (binder == null)
            {
                throw Error.ArgumentNull("binder");
            }

            // Add a provider so that we can use this type recursively
            // Be sure to insert at position 0 to preempt any eager binders (eg, MutableObjectBinder) that 
            // may eagerly claim all types.
            configuration.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(type, binder));

            // Add the binder to the list of rules. 
            // This ensures that the parameter binding will actually use model binding instead of Formatters.            
            // Without this, the parameter binding system may see the parameter type is complex and choose
            // to use formatters instead, in which case it would ignore the registered model binders. 
            configuration.ParameterBindingRules.Insert(0, type, param => param.BindWithModelBinding(binder));
        }
开发者ID:pingxumeng,项目名称:aspnetwebstack,代码行数:32,代码来源:HttpConfigurationExtensions.cs

示例6: Add

		public void Add(Type modelType, IModelBinder binder)
        {
            Precondition.Require(modelType, () => Error.ArgumentNull("modelType"));
			Precondition.Require(binder, () => Error.ArgumentNull("binder"));

            _mappings.Add(modelType, binder);
        }
开发者ID:radischevo,项目名称:Radischevo.Wahha,代码行数:7,代码来源:ModelBinderCollection.cs

示例7: GetPropertyValue

 /// <summary>
 /// This method changes de default behavior of a modelbinder when it has to bind a posted photo to the
 /// Photo property of customer picture. Otherwise it behaves default.
 /// </summary>
 /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
 /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
 /// <param name="propertyDescriptor">The descriptor for the property to access. The descriptor provides information such as the component type, property type, and property value. It also provides methods to get or set the property value.</param>
 /// <param name="propertyBinder">An object that provides a way to bind the property.</param>
 /// <returns>
 /// An object that represents the property value.
 /// </returns>
 protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
 {
     // Check to see if we are binding the Photo Property, otherwise fallback to default behavior
     if (propertyDescriptor.Name == "Photo")
     {
         IValueProvider provider = bindingContext.ValueProvider;
         // Check if there is a value on the request for the Photo property
         var result = provider.GetValue(bindingContext.ModelName);
         // The result should be a posted file
         HttpPostedFileBase file = result.ConvertTo(typeof(HttpPostedFileBase)) as HttpPostedFileBase;
         // Check if there's actually a Photo in the request.
         if (file == (HttpPostedFileBase)null)
         {
             //There is no photo.
             return null;
         }
         // Create a byte array with the length of the posted file.
         byte [] resultValue = new byte[file.ContentLength];
         // Read the contents of the posted file to the byte array.
         file.InputStream.Read(resultValue, 0, file.ContentLength);
         // Return the byte array.
         return resultValue;
     }
     //If we are binding another property fallback to default behavior.
     return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
 }
开发者ID:ljvblfz,项目名称:MicrosoftNLayerApp,代码行数:37,代码来源:CustomerPictureModelBinder.cs

示例8: GetPropertyValue

        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            var propertyType = propertyDescriptor.PropertyType;

            // Check if the property type is an enum with the flag attribute
            if (propertyType.IsEnum && propertyType.GetCustomAttributes(true).Any())
            {
                var providerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (providerValue != null)
                {
                    var value = providerValue.RawValue;
                    if (value != null)
                    {
                        // In case it is a checkbox list/dropdownlist/radio button list
                        if (value is string[])
                        {
                            // Create flag value from posted values
                            int flagValue = 0;
                            foreach (string val in ((string[])value))
                            {
                                flagValue = flagValue | (int)Enum.Parse(propertyType, val);
                            }
                            return Enum.ToObject(propertyType, flagValue);
                        }
                        // In case it is a single value
                        if (value.GetType().IsEnum)
                        {
                            return Enum.ToObject(propertyType, value);
                        }
                    }
                }
            }
            return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
        }
开发者ID:IDM3,项目名称:CharecterSheetTracker,代码行数:34,代码来源:Global.asax.cs

示例9: TryUpdateModel_ReturnsFalse_IfModelValidationFails

        public async Task TryUpdateModel_ReturnsFalse_IfModelValidationFails()
        {
            // Arrange
            var binders = new IModelBinder[]
            {
                new TypeConverterModelBinder(),
                new ComplexModelDtoModelBinder(),
                new MutableObjectModelBinder()
            };

            var validator = new DataAnnotationsModelValidatorProvider();
            var model = new MyModel();
            var modelStateDictionary = new ModelStateDictionary();
            var values = new Dictionary<string, object>
            {
                { "", null }
            };
            var valueProvider = new DictionaryBasedValueProvider(values);

            // Act
            var result = await ModelBindingHelper.TryUpdateModelAsync(
                                                    model,
                                                    "",
                                                    Mock.Of<HttpContext>(),
                                                    modelStateDictionary,
                                                    new DataAnnotationsModelMetadataProvider(),
                                                    GetCompositeBinder(binders),
                                                    valueProvider,
                                                    new[] { validator });

            // Assert
            Assert.False(result);
            Assert.Equal("The MyProperty field is required.",
                         modelStateDictionary["MyProperty"].Errors[0].ErrorMessage);
        }
开发者ID:Nakro,项目名称:Mvc,代码行数:35,代码来源:ModelBindingHelperTest.cs

示例10: BindWithModelBinding

        /// <summary>
        /// Bind the parameter using the given model binder. 
        /// </summary>
        /// <param name="parameter">parameter to provide binding for.</param>
        /// <param name="binder">model binder to use on parameter</param>
        /// <returns>a binding</returns>
        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, IModelBinder binder)
        {
            HttpConfiguration config = parameter.Configuration;
            IEnumerable<ValueProviderFactory> valueProviderFactories = new ModelBinderAttribute().GetValueProviderFactories(config);

            return BindWithModelBinding(parameter, binder, valueProviderFactories);
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:13,代码来源:HttpParameterDescriptorExtensions.cs

示例11: Remove

 /// <summary>
 /// Removes the specified model binder.
 /// </summary>
 /// <param name="binder">The model binder to remove.</param>
 public void Remove(IModelBinder binder)
 {
     var pairs = binders.Where(x => x.Value == binder).ToArray();
     foreach (var pair in pairs)
     {
         binders.Remove(pair.Key);
     }
 }
开发者ID:p69,项目名称:magellan-framework,代码行数:12,代码来源:ModelBinderDictionary.cs

示例12: GetPropertyValue

 /// <summary>
 /// Provides custom logic for creating an <see cref="ISectionID"/> object from a string.
 /// </summary>
 /// <param name="controllerContext"></param>
 /// <param name="bindingContext"></param>
 /// <param name="propertyDescriptor"></param>
 /// <param name="propertyBinder"></param>
 /// <returns></returns>
 protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
 {
     if (propertyDescriptor.PropertyType.IsSubclassOf(typeof(Section)))
       {
     return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, new SectionIdModelBinder());
       }
       // TODO: Account for a property that is a collection of ISection objects
       return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
 }
开发者ID:BellevueCollege,项目名称:ClassSchedule,代码行数:17,代码来源:SectionEditModelBinder.cs

示例13: TypeMatchModelBinderProvider

		public TypeMatchModelBinderProvider(Type type, IModelBinder binder)
			: base()
		{
			Precondition.Require(type, () => Error.ArgumentNull("type"));
			Precondition.Require(binder, () => Error.ArgumentNull("binder"));

			_type = type;
			_binder = binder;
		}
开发者ID:radischevo,项目名称:Radischevo.Wahha,代码行数:9,代码来源:TypeMatchModelBinderProvider.cs

示例14: RegisterDefaultModelBinderStartupTask

        public RegisterDefaultModelBinderStartupTask(IModelBinder modelBinder)
        {
            if (modelBinder == null)
            {
                throw new ArgumentNullException("modelBinder");
            }

            _modelBinder = modelBinder;
        }
开发者ID:bhaktapk,项目名称:com-prerit,代码行数:9,代码来源:RegisterDefaultModelBinderStartupTask.cs

示例15: GetPropertyValue

 /// <summary>
 /// Provides custom logic for creating an <see cref="ISectionID"/> object from a string.
 /// </summary>
 /// <param name="controllerContext"></param>
 /// <param name="bindingContext"></param>
 /// <param name="propertyDescriptor"></param>
 /// <param name="propertyBinder"></param>
 /// <returns></returns>
 protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
 {
     Type propertyType = propertyDescriptor.PropertyType;
       if (propertyType == typeof(SectionID) || propertyType.IsSubclassOf(typeof(SectionID)))
       {
     return SectionID.FromString(bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue);
       }
       return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
 }
开发者ID:BellevueCollege,项目名称:ClassSchedule,代码行数:17,代码来源:SectionIdModelBinder.cs


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